我很难理解如何在指令的特定实例上调用一个函数,如果它符合某些条件的话。在下面的示例中,如果键盘快捷键具有基于ng类的类,则当键盘快捷方式按下时,我希望调用特定指令实例上的函数。非常感谢您的帮助!
http://plnkr.co/edit/P7rM3o4TADSf6rxTIRsZ?p=preview
index.html
<body ng-controller="SampleController">
<test-question
ng-repeat="n in [1,2,3]"
ng-class="{'focused': tracer.focus == n}"
focusnum = "{{n}}"
ng-click="tracer.focus = n"
>
Test Question {{n}}
</test-question>
</body>script.js
angular.module('sampleApp', [])
.controller("SampleController", function($scope) {
$scope.tracer = {
focus: 1
}
// on keyboard shortcut call some function on a specific directive with class focused
})
.directive('testQuestion', function() {
return {
restrict: 'E',
link: function(scope, el, attrs) {
scope.someFunction = function() {};
}
}
});发布于 2015-01-06 04:33:55
将script.JS更改为如下所示:
// Code goes here
angular.module('sampleApp', [])
.controller("SampleController", function($scope) {
$scope.tracer = {
focus: 1
}
// on keypress call directive function that has class focused
})
.directive('testQuestion', ['$document',
function($document) {
return onUserKeyPress;
}
]);
var onUserKeyPress = function(scope, element, attributes) {
element.on('click', onClick);
}
var onClick = function(event) {
alert('clicked');
}谢谢,
发布于 2015-01-06 04:46:13
我想这里的关键是-你想把键盘事件附加到静态的html!为此,您需要添加tabindex。
在html中的更改
<test-question ng-enter="doWhatever()" tabindex="0"
ng-repeat="n in [1,2,3]"
ng-class="{'focused': tracer.focus == n}"
focusnum = "{{n}}"
ng-click="tracer.focus = n"
>
Test Question {{n}}
</test-question>对脚本的更改
.directive('ngEnter', function () {
return function (scope, element, attrs) {
element.bind("keydown keypress", function (event) {
if(event.which === 13) {
scope.$apply(function (){
console.log("In your directive....")
scope.$eval(attrs.ngEnter);
});
event.preventDefault();
}
});
};
});;参考 :http://plnkr.co/edit/vho0BPfGPW2zE5OYHkgP?p=preview
如需解释,请参阅How can I give keyboard focus to a DIV and attach keyboard event handlers to it?
https://stackoverflow.com/questions/27791941
复制相似问题