Created
May 27, 2016 07:51
-
-
Save singhmohancs/317854a859098bffe9477f59eac8d915 to your computer and use it in GitHub Desktop.
input enter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @ngDoc Directive | |
* @name app.Directive.onKeyEnter | |
* @module app | |
* | |
* @description | |
* this directive triggers callback function when enter key is pressed | |
* | |
* @author Mohan Singh <mslogicmaster@gmail.com> | |
* | |
*/ | |
angular | |
.module('app', []); | |
angular | |
.module('app') | |
.directive('onKeyEnter', ['$parse', function($parse) { | |
return { | |
restrict: 'A', | |
link: function(scope, element, attrs) { | |
element.bind('keydown keypress', function(event) { | |
if (event.which === 13) { | |
var attrValue = $parse(attrs.onKeyEnter); | |
(typeof attrValue === 'function') ? attrValue(scope) : angular.noop(); | |
event.preventDefault(); | |
} | |
}); | |
scope.$on('$destroy', function() { | |
element.unbind('keydown keypress') | |
}) | |
} | |
}; | |
}]); |
1.- why do you pass the scope on line 24?
$parse(attrs.onKeyEnter)
Converts AngularJS expression into a function. onKeyEnter
is an Angular Expression here.
$parse(attrs.onKeyEnter)
returns a function(context, locals)
where context
is scope
.
More Info: https://docs.angularjs.org/api/ng/service/$parse
2.- what do you do on line 28?
It is a best practice to unbind events from the element when it is not used. scope.$on('$destroy', function() {
is an event when a directive is destroyed in that case, all attached events should be detached.
@zorlac
Binding does work perfectly. if (event.which === 13) {
does trigger angular Expression when ENTER
key is pressed.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Bindings doesn't refresh when a value is change inside the function invoke by keypress. Do you need to invoke digest after calling the function?