Can anyone provide some insight on why my JavaScript key code isn't working as expected in the second directive of my example below? It seems that injecting scope attributes is causing the function passed into the directive not to be evaluated properly. The first directive, however, works fine without any scope injection.
Could this be intended behavior or am I making a mistake somewhere?
angular.module('taskLister', []);
angular.module('taskLister')
.controller('ListController', ListController);
ListController.$inject = ['$log'];
angular.module('taskLister')
.directive('keyPresser', keyPresser);
keyPresser.$inject = ['$log'];
angular.module('taskLister')
.directive('keyPresserNotWorking', keyPresserNotWorking);
keyPresserNotWorking.$inject = ['$log'];
function ListController($log) {
var vm = this;
vm.editingListTitle = false;
vm.editListTitle = editListTitle;
vm.finishedEditListTitle = finishedEditListTitle;
function editListTitle() {
vm.editingListTitle = true;
$log.info('editing');
}
function finishedEditListTitle() {
vm.editingListTitle = false;
$log.info('finished editing');
}
}
//********
//Working
//********
function keyPresser($log) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
element.bind('keydown keypress', function(event) {
if (event.which === 13) {
scope.$apply(function() {
scope.$eval(attrs.keyPresser);
});
event.preventDefault();
}
});
}
};
}
//********
//Not Working
//********
function keyPresserNotWorking($log) {
return {
restrict: 'A',
scope: {
key: '@key'
},
link: function(scope, element, attrs) {
element.bind('keydown keypress', function(event) {
scope.key = Number(scope.key);
if (event.which === scope.key) {
scope.$apply(function() {
scope.$eval(attrs.keyPresserNotWorking);
});
event.preventDefault();
}
});
}
};
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js"></script>
<div ng-app="taskLister">
<div ng-controller="ListController as vm">
has the user pressed enter? - {{vm.editingListTitle}}
<br/>
<input type="text" key-presser="vm.editListTitle()" placeholder="Press Enter">
<br/>
<input type="text" key-presser-not-working="vm.editListTitle()" key="13" placeholder="Press Enter but it doesnt work">
<br/>
<button ng-click="vm.finishedEditListTitle()" type="button">Reset</button>
<br/>
</div>
</div>
Appreciate any help provided! :)