我有兩個嵌套的ng-repeat
在我都積極使用各自$index
。爲了便於閱讀,我使用ng-init
(即:ng-init="backupIndex = $index"
)「重新命名」第一個$索引。在起點上,一直很好,並且backupIndex
總是等於$index
。
問題是如果我從綁定到ng-repeat
的集合中刪除元素,則backupIndex
將與$index
不同步。
這裏是plunker。我如何維護$index
和backupIndex
同步?
我有兩個嵌套的ng-repeat
在我都積極使用各自$index
。爲了便於閱讀,我使用ng-init
(即:ng-init="backupIndex = $index"
)「重新命名」第一個$索引。在起點上,一直很好,並且backupIndex
總是等於$index
。
問題是如果我從綁定到ng-repeat
的集合中刪除元素,則backupIndex
將與$index
不同步。
這裏是plunker。我如何維護$index
和backupIndex
同步?
你可以做到這一點,如果ü可以省略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>
這條線將分配的$index
backupIndex
值,它會與$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
就是這樣。
您不需要將第一個索引重命名爲backupIndex,因爲每個ng-repeat都會創建一個新的範圍,並且如果您在第二個ng-repeat中並且想要到達第一個索引,您只需要做是訪問,使用
$parent.$index
您需要在後期提供更多的代碼,不僅在plunker – Grundy
爲什麼你_backupIndex_需要,而不是你可以使用_ $ INDEX_直接 – Grundy