我怎么能告诉哪个ng-repeat项是指令回调的来源?

时间:2015-09-15 11:26:00

标签: javascript angularjs angularjs-directive

我有一个可以使用回调参数调用的下拉指令。然后,当用户在下拉列表中选择一个选项时,将从该指令调用此回调。一个工作回调函数如下所示:

myDirectiveCallback(selectedItem){
    //Do something with the selectedItem
}

我想在ng-repeat中使用此指令,我希望能够知道选择中的哪一个下拉列表(ng-repeat中的哪个项目)以及从中调用回调。 / p>

<div ng-repeat="item in myListOfItems">
    <my-directive callback="myDirectiveCallback"></my-directive>
</div>

有没有办法在不更新指令的情况下这样做?

1 个答案:

答案 0 :(得分:1)

在你的指令中添加另一个属性,以便你可以传递它item然后在指令范围内引用它,这样你就可以将它传递给你的回调(或者你需要的其他任何东西)。 / p>

你没有包含你的指令代码,所以我只想告诉你我的意思:

myApp.directive('myDirective', function() {
  return {
    restrict: 'A',
    transclude: true,
    scope: {
      currentItem: '=currentItem'  // could just use '=' since names match
    },
    templateUrl: 'myTemplate.html'
  };
});

然后将currentItem属性与当前项一起添加到指令调用:

<div ng-repeat="item in myListOfItems">
    <my-directive currentItem="item" callback="myDirectiveCallback"></my-directive>
</div>