首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从控制器调用特定指令实例的函数

从控制器调用特定指令实例的函数
EN

Stack Overflow用户
提问于 2015-01-06 04:06:09
回答 2查看 166关注 0票数 1

我很难理解如何在指令的特定实例上调用一个函数,如果它符合某些条件的话。在下面的示例中,如果键盘快捷键具有基于ng类的类,则当键盘快捷方式按下时,我希望调用特定指令实例上的函数。非常感谢您的帮助!

http://plnkr.co/edit/P7rM3o4TADSf6rxTIRsZ?p=preview

index.html

代码语言:javascript
复制
<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

代码语言:javascript
复制
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() {};
        }
    }
  });
EN

回答 2

Stack Overflow用户

发布于 2015-01-06 04:33:55

将script.JS更改为如下所示:

代码语言:javascript
复制
// 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');
  }

谢谢,

票数 0
EN

Stack Overflow用户

发布于 2015-01-06 04:46:13

我想这里的关键是-你想把键盘事件附加到静态的html!为此,您需要添加tabindex

在html中的更改

代码语言:javascript
复制
<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>

对脚本的更改

代码语言:javascript
复制
.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?

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27791941

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档