I'm trying to write an AngularJS directive to run a function when the Escape key is pressed:
HTML
<input type="text" custom-keypress="consoleLog()">
JS
var app = angular.module('app', []);
app.controller('appCtrl', function($scope) {
$scope.consoleLog = function () {
console.log('works')
}
});
app.directive('customKeypress', function () {
return function (scope, element, attrs) {
element.bind("keydown keypress", function (event) {
if(event.which === 27) {
scope.$apply(function (){
scope.$eval(attrs.ngEnter);
});
event.preventDefault();
}
});
};
});
Unfortunately when I press the Escape key nothing happens.
Any idea what I'm doing wrong?
you are targeting the wrong attribute value on your $eval
call. Forked and fixed - http://plnkr.co/edit/0fsKoHAAgTvl4l2z8SfJ?p=preview
should be: scope.$eval(attrs.customKeypress);