Execute on enter angular directive

by robcampo

HTML

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js"></script>
<script src="http://code.angularjs.org/1.2.13/angular-animate.min.js"></script>
<div ng-app="App" ng-controller="MyCtrl">
    <input type="text" execute-on-enter="buttonClicked"/>
    <button ng-click="buttonClicked()">Click Me</button>
    
    <div>Button clicked {{numClicks}} times</div>
</div>

JavaScript

angular.module('App', ['ngAnimate']);

/**
 * This directive listens out for the enter key to be pressed and runs a particular function
 * (defined by the value passed into it from the HTML). For example, if you have an input field:
 *
 *      <input type="text" execute-on-enter="searchClicked" />
 *
 * the 'searchClicked' function will be executed when enter is clicked on this input form. This
 * makes it easier for the user so they don't have to click a button each time they write text.
 */
 
angular.module("App").directive("executeOnEnter", function() {
    return {
        restrict: "A",
        link: function(scope, element, attrs) {
 
            // When the user starts typing in the input field
            element.keyup(function(event){
                // If the key entered is an enter key
                if(event.keyCode == 13){
                    // Get the function to execute
                    var exeFunction = scope[attrs.executeOnEnter];
 
                    // And run it if it exists
                    if (exeFunction) {
                        exeFunction()
                    }
                }
            })
        }
    }
});

angular.module("App").controller("MyCtrl", function($scope) {
    
    $scope.numClicks = 0;
    
    $scope.buttonClicked = function() {
        $scope.numClicks++;
    }
    
});