2013-11-26 15 views
1

我曾試圖得到這樣如何通過指令在AngularJS中查找索引?

指數,這是我的HTML

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

這是控制器

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

我在這裏能夠得到指數value.but我想指數價值通過指令

這是我的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); 
       }); 
     }); 
    }; 

這裏我不能夠得到index..so如何在指令中獲得的索引值?

+0

你真的應該考慮使用一個孤立的範圍這樣的事情。指令依賴'$ index'是不好的做法。看到我的答案闡述。 –

回答

5

ngRepeat每個迭代都有不同的範圍。使用scope訪問各指標:

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

Fiddle

+0

感謝您的回答...但我無法獲得父母索引...我已經嘗試過這樣的範圍。$ parent。$ index但這不起作用.... – silvesterprabu

+0

@silvesterprabu您將能夠訪問'$ parent。$ index'只有當你嵌套'ng-repeat'時。 – AlwaysALearner

+0

是的,我嵌套ng重複... – silvesterprabu

4

我有一個應用程序看起來像這樣,和它的作品。不需要綁定到$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這樣的封裝。它要求它在一箇中繼器內,這也會破壞封裝。

取而代之,請考慮使用隔離的作用域並將值傳遞給via參數。

的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); 
     }); 
    } 
    }; 
}); 

Working Codepen

祝你好運!

0

使用該指令屬性「讓IND =指數」

例如:

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