2015-05-13 28 views
0

我有兩個嵌套的ng-repeat在我都積極使用各自$index。爲了便於閱讀,我使用ng-init(即:ng-init="backupIndex = $index")「重新命名」第一個$索引。在起點上,一直很好,並且backupIndex總是等於$index

問題是如果我從綁定到ng-repeat的集合中刪除元素,則backupIndex將與$index不同步。

這裏是plunker。我如何維護$indexbackupIndex同步?

+0

您需要在後期提供更多的代碼,不僅在plunker – Grundy

+0

爲什麼你_backupIndex_需要,而不是你可以使用_ $ INDEX_直接 – Grundy

回答

1

你可以做到這一點,如果ü可以省略ng-init一部分,

<ul ng-repeat="value in values"> 
    <span style="display: none"> {{ backupIndex = $index }}</span> 
    <li>backUp: <b>{{backupIndex}}</b> $index: <b>{{$index}}</b> <button ng-click="rem(backupIndex)">Remove</button></li> 
</ul> 

<span style="display: none"> {{ backupIndex = $index }}</span>這條線將分配的$indexbackupIndex值,它會與$index

這裏同步是DEMO


<ul ng-repeat="value in values" ng-init="backupIndex = $index">

ng-init將只執行一次,它會創建一個ng-repeat的叫backupIndex子範圍變量,並將它的$index的價值和backupIndex不與$index同步。

var ngInitDirective = ngDirective({ 
    priority: 450, 
    compile: function() { 
     return { 
      pre: function(scope, element, attrs) { 
       scope.$eval(attrs.ngInit); 
      } 
     }; 
    } 
}); 

這是angular.js指令爲ng-init。它的作用是獲得ng-init中的表達式,並在當前範圍內執行表達式並返回結果。

在這種情況下:ng-init表達是backupIndex = $index然後在scope.$eval(attrs.ngInit);attrs.ngInit由具有backupIndex = $index表達)backupIndex = $index表達對ng-repeat的範圍執行。這意味着在ng-repeat的範圍內有一個名爲backupIndex的變量,其值爲$index就是這樣。

+0

你能解釋一下爲什麼' ng-init'不起作用? – lvarayut

+0

@Lavarayut _ngInit_只運行鏈接功能 – Grundy

0

您不需要將第一個索引重命名爲backupIndex,因爲每個ng-repeat都會創建一個新的範圍,並且如果您在第二個ng-repeat中並且想要到達第一個索引,您只需要做是訪問,使用

$parent.$index 

DEMO:http://plnkr.co/edit/w8btAZfbGgNGLoYFCTP2?p=preview