我有一个可以使用回调参数调用的下拉指令。当用户在下拉列表中选择一个选项时,会从指令中调用此回调。工作回调函数如下所示:
myDirectiveCallback(selectedItem){
//Do something with the selectedItem
}
我想在 ng-repeat 中使用此指令,并且希望能够知道在哪个下拉列表(ng-repeat 中的哪一项)中进行了选择并从其中调用了回调。
<div ng-repeat="item in myListOfItems">
<my-directive callback="myDirectiveCallback"></my-directive>
</div>
有没有办法在不更新指令的情况下做到这一点?
最佳答案
向您的指令添加另一个属性,以便您可以传递它item
,然后在指令范围内引用它,以便您可以将它传递给您的回调(或您需要它的任何其他内容) )。
您没有包含指令代码,因此我将尝试向您展示我的意思:
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>
关于javascript - 我怎样才能知道指令回调是由哪个 ng-repeat 项组成的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32584815/