我无法理解如何在指令的特定实例上调用函数(如果它满足某些条件)。在下面的示例中,如果特定指令实例的类基于 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() {};
}
}
});
最佳答案
将 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');
}
谢谢,
关于javascript - 从 Controller 调用特定指令实例的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27791941/