如果符合某些条件,我无法理解如何在指令的特定实例上调用函数。在下面的示例中,我想在按下键盘快捷键时调用特定指令实例上的函数,如果它具有基于ng-class的类集中。非常感谢您的帮助!
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() {};
}
}
});
答案 0 :(得分:0)
将您的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');
}
谢谢,
答案 1 :(得分:0)
我想这里的关键点是 - 你想将键盘事件附加到静态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?
进行解释