我有一个todo列表,使用js:
function todoCtrl($scope) {
$scope.todos = S('todos', []);
$scope.addTodo = function() {
$scope.todos.unshift({
text: $scope.todoText,
done: false
});
$scope.todoText = '';
}
$scope.remove = function($index) {
$scope.todos.splice($index, 1);
}
}
和html是:
<div id="scope" ng-controller="todoCtrl">
<div id="todoAdd">
<h3>Todo List</h3>
<form ng-submit="addTodo()">
<input class="input" ng-model="todoText"/>
</form>
</div>
<div style="margin-top:120px;" id="todolist">
<div style="width:320px;margin-left:42px;margin-top:40px;" ng-repeat="todo in todos track by $index">
<input type="checkbox" class="checkbox" ng-model="todo.done" ng-change="todochange(todo)">
<p class="todoP todo{{todo.done}}" ng-click="remove($index)">{{todo.text}}</p>
</div>
</div>
</div>
然后我添加了ng-animate css:
.ng-enter
{
-webkit-transition: 1s;
opacity:0;
}
.ng-enter-active
{
opacity:1;
}
.ng-leave
{
-webkit-transition: 1s;
}
.ng-leave-active
{
opacity:0;
}
问题是当我添加或删除项目时,总是最后一项fadeIn或fadeOut,而不是我添加或点击的元素。为什么?请告诉我。
答案 0 :(得分:3)
此问题的根本原因是ngRepeat DOM通过使用&#34; track by&#34;与$ index相关联。表达。通过&#34;跟踪&#34;在ng-repeat指令中,只有在&#34;中定义的对象和DOM之间的关联通过表达式&#34;时,Angular才会销毁/重新创建DOM。不存在。
让我们发现&#34;跟踪$ index&#34;工作并弄清楚当用户添加/删除待办事项时,为什么最后一项总是淡入/淡出。
我们假设todo数据为空,重复的DOM为:
<div>{{todo.text}}</div>
数据:强>
todos = [{text:"0",done:false}];
$ index与DOM之间的关联:
$index0 <=====> <div>0</div> //new association
因为这种关联不存在,所以DOM&#34; 0&#34;会消失。
数据:强>
todos = [{text:"1",done:false},{text:"0",done:false}];
$ index与DOM之间的关联:
$index0 <====> <div>1</div>
$index1 <====> <div>0</div> //new association
再次,新关联:$ index1&lt; ====&gt; 0不存在,创建一个新的DOM和fadeIn。您可以发现fadeIn DOM将始终是ngRepeat列表的最后一项。
假设todo数据是
[{text:"3",done:false},{text:"2",done:false},{text:"1",done:false},{text:"0",done:false}]
数据:强>
todos = [{text:"3",done:false},{text:"1",done:false},{text:"0",done:false}];
$ index与DOM之间的关联:
$index0 <=====> <div>3</div>
$index1 <=====> <div>1</div>
$index2 <=====> <div>0</div>
$index3 // removed association
$ index3和DOM之间的关联不存在,因此删除DOM和待办事项fadeOut。
因为$ index是DOM的标识符,所以ng-repeat列表的最后一项始终是创建/销毁的DOM。如果你想从&#34;跟踪&#34;表达式,尝试使用:
ng-repeat="todo in todos track by $id(todo)"