我为快捷方式提供了服务。
看起来像:
angular.module('myApp.services.shortcuts', [])
.factory('Shortcuts', function($rootScope) {
var service = {};
service.trigger = function(keycode, items, element) {
// write the shortcuts logic here...
}
return service;
})
然后我将它注入到控制器中:
angular.module('myApp.controllers.mainCtrl', [])
.controller('mainCtrl', function($scope, $element, $document, Shortcuts) {
// whatever blah blah
$document.on('keydown', function(){
// skip if it focused in input tag
if(event.target.tagName !== "INPUT") {
Shortcuts.trigger(event.which, $scope.items, $element);
}
})
})
它可以工作,但你可能会注意到我将 $element 和 $document 注入到控制器中。
这是一种不好的控制器做法,违反了“永远不要在控制器中访问 $element”的约定。
我应该把它放入指令中,然后使用'ngKeydown'和$event来触发服务。
但我觉得服务还不错,我会尽快返工控制器。
更新:
似乎 'ng-keydown' 只适用于输入标签。
所以我只是写了一个指令并注入$document:
angular.module('myApp.controllers.mainCtrl', [])
.directive('keyboard', function($scope, $document, Shortcuts) {
// whatever blah blah
return {
link: function(scope, element, attrs) {
scope.items = ....;// something not important
$document.on('keydown', function(){
// skip if it focused in input tag
if(event.target.tagName !== "INPUT") {
Shortcuts.trigger(event.which, scope.items, element);
}
})
}
}
})
这样更好。