使用$ index进行跟踪时,ng-init没有第二次调用 [英] ng-init is not calling second time when track by $index used
问题描述
html:
<table>
<tbody>
<tr ng-repeat="row in Rows track by $index" ng-init="initUserDecision(row,$index)" >
<td>{{employeeName}}</td>
</tr>
</table>
<button id="change"/>
控制器:
$scope.initUserDecision = function(row,index){
$scope.employeeName=row["name"];
}
$scope.rows=[{id:1,name:'siva'},{id:2,name:'ram'}]
//changing $scope.rows in button click event and used $scope.$apply as well
angular.element(document).on("click", "#change", function () {
$scope.rows=[{id:1,name:'ravi'},{id:2,name:'raj'}]
$scope.$apply();
});
tr初始化时,
ng-init
函数首次调用.如果我单击更改"按钮,则行集合被更改并且不会再次调用ng-init
.如果我通过两次调用$index
ng-init
删除曲目.当我通过$index
使用track时,它只被调用了一次.为什么会这样呢?关于这个的任何想法.
ng-init
function calling first-time when tr initialized. if i click change button rows collection gets changed and it won't calling ng-init
again. if i remove track by $index
ng-init
calling both the times. when i use track by $index
it was called only one time. why is it so ? Any idea about this.
推荐答案
使用track by $index
时.手表由index
而不是uid
保留在collection
中的data item
上.
When you use track by $index
. Watch is kept on data item
in collection
by their index
and not by uid
.
-
not track by
,
在这种情况下,ngRepeat
每当collection is updated
时在集合中为data item
创建new uid
. ngRepeat
看到new uids
和re-renders
所有元素.
In this case, ngRepeat
create new uid
for data item
in collection whenever collection is updated
. ngRepeat
sees new uids
and re-renders
all elements.
track by,($index)
在这种情况下,ngRepeat
将index as uid
用于收集中的数据项. ngRepeat
没有看到任何new uids
,因此也没有看到no re-rendering
的元素(添加或删除,如果有,则为no rendering of others
). (由于watch
保留在数据上,它将获得updated
但没有呈现)
In this case, ngRepeat
uses index as uid
for data item in collection. ngRepeat
doesn't see any new uids
and hence no re-rendering
of elements (add or remove,if any, but no rendering of others
). (As watch
is kept on data, it will get updated
but no-rendering)
这篇关于使用$ index进行跟踪时,ng-init没有第二次调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!