I'm attempting to create a directive that binds specific keypresses to functions specified in the scope of a controller, but all of the callback functions seem to be overridden by the last callback function in the object containing the bindings. I've tried using keymaster.js and mousetrap.js for binding the events with the same results.
The Javascript code:
angular.module('app', ['directives', 'controllers']);
angular.module('directives', [])
.directive('keypress', [function () {
return function (scope, element, attrs) {
// console.log(scope, element, attrs);
var attribute = scope.$eval(attrs.keypress || '{}');
for (var k in attribute) {
console.log('binding ' + k + ' as ' + attribute[k]);
Mousetrap.bind(k, function() { return attribute[k](scope, element); });
}
};
}]);
angular.module('controllers', [])
.controller('TodoController', function($scope) {
$scope.shortcuts = {
'w': function () { console.log('w'); },
's': function () { console.log('s'); },
'a': function () { console.log('a'); },
'd': function () { console.log('d'); }
};
});
The HTML File:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular.js"></script>
<script src="https://raw.github.com/ccampbell/mousetrap/master/mousetrap.min.js"></script>
<script src="/javascript/app.js"></script>
</head>
<body>
<div ng-app="app">
<div ng-controller='TodoController' keypress='shortcuts'>Foo</div>
</div>
</body>
</html>
Why is 'd' always written to the console, regardless of whether I press 'w', 'a', 's', or 'd'?