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

sil*_*abu 1 javascript angularjs

我试图得到像这样的索引

这是我的HTML

  <div ng-repeat="item in items" ng-click="findindex($index)"></div>
Run Code Online (Sandbox Code Playgroud)

这是控制器

 $sceop.findinedx=function(index)
{
    alert(index);
}
Run Code Online (Sandbox Code Playgroud)

在这里,我能够得到索引值.但我想通过指令得到索引值

这是我的HTML

 <div ng-repeat="item in items" my-directive></div> 
Run Code Online (Sandbox Code Playgroud)

这是我的指示

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

在这里我无法获得index..so如何在指令中获取索引值?

Alw*_*ner 5

每个ngRepeat迭代都有不同的范围.使用scope访问各指标:

elem.bind('click', function($index){
    alert(scope.$index);
});
Run Code Online (Sandbox Code Playgroud)

Fiddle


Bri*_*sio 5

我有一个看起来像这样的应用程序,并且它可以工作。无需绑定到$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);
    });
  };
});
Run Code Online (Sandbox Code Playgroud)

但是,你应该重新考虑

以这种方式编写指令是不好的做法。指令的关键概念之一是它们应该封装行为。您通过让指令查看$index类似的内容来破坏封装。它要求它位于中继器内,这也会破坏封装。

相反,请考虑使用隔离范围并通过参数传递值。

HTML 看起来像这样:

<div ng-repeat="item in items" my-directive="item" index="$index"></div>
Run Code Online (Sandbox Code Playgroud)

然后使用隔离范围稍微不同地定义该指令:

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);
      });
    }
  };
});
Run Code Online (Sandbox Code Playgroud)

工作代码笔

祝你好运!