我想知道是否可以在按下全局键盘快捷键的情况下调用特定指令实例上的函数,如果它具有基于ng-class 的类集中。
以下是一些模板代码:
home.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>
home.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)
尝试从另一个角度来看它。创建一个绑定到主控制器中的值的指令。用该指令监视该值以及何时设置为true,例如,在指令中调用该方法。
在主控制器中,您可以使按键快捷键根据主控制器中保持的焦点将必要值设置为true。像这样的东西
angular.module('sampleApp', []).controller("SampleController", function($scope) {
$scope.childDirectiveFlags = {dir1:false,dir2:false,dir3:false};
$scope.currentFocus = 'dir1';
// on keypress event set the flag to true in the directive you want action to
// happen on
$scope.childDirectiveFlags[$scope.currentFocus] = true; // Will trigger watch
};
sampleApp.directive = directive('testQuestion', function() {
return {
restrict: 'E',
scope : {
watchValue: '@'
},
link: function(scope, el, attrs) {
scope.$watch('watchValue',function() {
if(scope.watchValue) {
scope.someFunction();
scope.watchValue = false;
}
});
scope.someFunction = function() {};
}
}
});