Javascript 按键盘上特定指令实例的函数调用

Javascript 按键盘上特定指令实例的函数调用,javascript,angularjs,Javascript,Angularjs,我想知道当按下全局键盘快捷键时,是否可以在特定的指令实例上调用函数,如果该快捷键的类基于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 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>

试着从另一个角度看问题。制作一个绑定到主控制器中的值的指令。在该指令中观察该值,例如,当它设置为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() {};
           }
         }
     });

谢谢斯科特!有没有一种方法可以在不存储
$scope.childDirectiveFlags={dir1:false,dir2:false,dir3:false}的情况下执行此操作在模型中?因为我们已经有了正确的指令,所以我认为可能有一些方法可以使用它们的属性,而不是针对特定的指令。当然还有$rootscope.broadcast特性。但这仍然会调用所有指令,这似乎不是最有效的方法。当然,只要绑定到它,就可以使用任何值。这只是一个示例。
     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() {};
           }
         }
     });