javascript - 从 Controller 调用特定指令实例的函数

标签 javascript angularjs

我无法理解如何在指令的特定实例上调用函数(如果它满足某些条件)。在下面的示例中,如果特定指令实例的类基于 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/

相关文章:

javascript - 在 md-autocomplete 列表中添加分隔符

javascript - Angular $window.scrollTo() 不起作用

angularjs - 从浏览器中删除 yeoman 图像

javascript - 在 Artillery 中跨 YAML 文件使用全局变量

javascript - ReactJS - 组件在父亲重新渲染后仍然存在

javascript - 为什么上个月的 12.31.2013 是 12.01.2013?

javascript - 如何在不四舍五入的情况下删除尾随小数?

javascript - 使用innerHTML和vanilla JS检索节点的内容

angularjs - 如何在 Chutzpah 的 headless 浏览器中使用 templateUrl 测试指令

javascript - 无法从 JSON 访问对象