无法从指令调用父控制器方法

Unable to call parent controller method from directive

我已经看到 many, many, many, many 关于这个问题的问题,但出于某种原因,我 仍然 无法在我的指令中将 ng-click 绑定到方法在父控制器上。我很确定我的范围隔离和方法参数传递正确但到目前为止运气不好。我的 JS 的粗略简化(这个应用程序很大)如下所示:

angular.module('myApp', []);

angular.module('myApp').directive('myCustomDirective', customDirective);

function customDirective() {
  return {
    restrict: 'E',
    scope: {
      myCallback: '&myCallback'
    }
    template: '<div><h3>My directive</h3><p>I am item {{itemIndex}}</p><button ng-click="myCallback({itemIndex: itemIndex})">Click to call back</button></div>'
  }
}

angular.module('myApp').controller('myController', myController);

function myController() {
  var vm = this;
  vm.selectedIndex = -1;

  vm.items = [0, 1, 2, 3, 4];

  vm.callbackMethod = function(itemIndex) {
    vm.selectedIndex = itemIndex;
  }
}

类似的简化标记如下所示:

<!DOCTYPE html>
<html ng-app="myApp">

  <head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.js"></script>
    <script src="script.js"></script>
  </head>

  <body>
    <div ng-controller="myController as test">
      <p>Selected item: {{test.selectedIndex}}</p>
      <my-custom-directive my-callback="test.callbackMethod" ng-repeat="item in test.items" ng-init="itemIndex = $index"></my-custom-directive>
    </div>
  </body>

</html>

我在这里不知所措,因为我已经关注了每个 SO post 和有关该主题的博客,但仍然一无所获。更糟糕的是,我用来说明这个问题的 Plunk 也不起作用 ($injector:nomod) - 如果有人能找出原因,加分! ;-)

您应该使用参数定义方法,而不是将其引用放在指令元素上。

my-callback="test.callbackMethod(itemIndex)" 

还通过将当前元素索引添加到独立范围内来将其传递给指令。

scope: {
  myCallback: '&myCallback',
  itemIndex: '='
},

Demo Here

我在你的指令中添加了一个额外的属性并删除了 ng-init。

 <my-custom-directive my-callback="test.callbackMethod($index)" ng-repeat="item in test.items track by $index" theindex="$index"></my-custom-directive>

Example