Hi,

Today, I’ll share my first tip for AngularJs. This is something very simple but this can be usefull.

zzEnter

zzEnter is a directive that allows you to call a function when using “Enter” key on your keyboard when typing an input.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
angular.module('zzEnter', [])
.directive('zzEnter', function () {
return function (scope, element, attrs) {
element.bind("keydown keypress", function (event) {
if(event.which === 13) {
scope.$apply(function (){
scope.$eval(attrs.zzEnter);
});
event.preventDefault();
}
});
};
})

How to

  • Declare the module in your html
1
<script src="js/zzEnter.js"></script>
  • Add the module in your application
1
2
angular.module('myApp', ['zzEnter'])
// ...
  • use it like so :

    • in the controller

      1
      2
      3
      4
      5
      6
      .controller('myController', ['$scope', function($scope) {
      $scope.foo = "bar";
      $scope.sayHello = function() {
      alert('Hello, ' + ($scope.foo || 'World') + '!');
      }
      });
    • in the view

      1
      <input ng-model="foo" zz-enter="sayHello()">

So, now when you use “Enter” key on this input, you should be alerted with “Hello, [what you entered in the input]!” .


Did you like it ? Did you find it usefull? let me know in the comments …