如何通过指令在AngularJS中查找索引

How to find index in AngularJS through directive?

本文关键字:查找 索引 AngularJS 何通过 指令      更新时间:2023-10-09

我试着得到这样的索引

这是我的html

  <div ng-repeat="item in items" ng-click="findindex($index)"></div>

这是控制器

 $sceop.findinedx=function(index)
{
    alert(index);
}

这里我可以得到索引值。但我想通过指令得到索引值

这是我的html

 <div ng-repeat="item in items" my-directive></div> 

这是我的指示

   app.directive('myDirective',function()
   {
        return function(scope, elem, attrs,$index) 
        {
              elem.bind('click', function($index)
              {
                   alert($index);
              });
        });
   };

这里我无法获取索引。。那么如何在指令中获取索引值呢?

我有一个看起来像这样的应用程序,它可以工作。无需绑定到$parent。一切都在你的范围内,因为指令除了默认范围之外没有定义任何其他内容:

http://codepen.io/BrianGenisio/pen/yFbuc

var App = angular.module('App', []);
App.controller('TestCtrl', function($scope) {
  $scope.items = ['a', 'b', 'c'];
});
App.directive('myDirective',function() {
  return function(scope, elem, attrs,$index) {
    elem.html(scope.item)
    elem.bind('click', function($index) {
      alert(scope.$index);
    });
  };
});

但是,您应该重新认识

以这种方式编写指令是不好的做法。指令的一个关键概念是它们应该封装行为。通过让指令像那样窥探$index,您正在破坏封装。它要求它在中继器内部,这也破坏了封装。

相反,可以考虑使用一个独立的作用域,并通过参数传入值。

HTML看起来像这样:

<div ng-repeat="item in items" my-directive="item" index="$index"></div>

然后,您可以使用一个独立的范围来定义不同的指令:

App.directive('myDirective',function() {
  return {
    scope: {
     index: '=',
     item: '=myDirective'
    },
    link: function(scope, elem, attrs,$index) {
      elem.html(scope.item)
      elem.bind('click', function($index) {
        alert(scope.index);
      });
    }
  };
});

工作代码笔

祝你好运!

每个ngRepeat迭代都有不同的范围。使用scope访问各自的索引:

elem.bind('click', function($index){
    alert(scope.$index);
});

Fiddle

在指令属性"let ind=index"中使用

例如:

<ul>
    <li *ngFor="let i of items; let ind= index">
        {{i}}
        <span (click)="removeItem()" class="remove_link">X</span>
    </li>
</ul>