如何通过指令在AngularJS中查找索引
How to find index in AngularJS through directive?
我试着得到这样的索引
这是我的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>
相关文章:
- Javascript:根据对象的嵌套数组中的值,在数组中查找对象的索引
- 在从索引位置返回的字符串中查找空白
- 查找字符串及其索引中的最大数字
- 在 jquery 选项卡中查找 span 标记并返回该索引
- 给定一个带有数字的数组,我如何编写一个递归函数,当 2 个元素加起来为一个目标时,它会在数组中查找索引
- 查找数组中项目包含子字符串的索引
- 按键查找数组中对象的索引
- 查找所选元素的索引
- Typescript,NodeJS,ES6-在数组上查找索引
- 如何通过指令在AngularJS中查找索引
- 在与加载的数组不同的数组中查找索引
- 在对象数组中查找索引
- D本地查找索引数据库错误
- 按ID快速查找索引
- 在二维数组中查找索引
- JavaScript:查找索引的一些值在excel从JavaScript
- 如何根据兄弟元素中排序的元素查找索引
- Lodash查找索引不工作
- javascript查找索引问题与IE
- 在数组范围中查找索引