当使用 $index 跟踪时,ng-init 不会第二次调用 [英] ng-init is not calling second time when track by $index used

查看:27
本文介绍了当使用 $index 跟踪时,ng-init 不会第二次调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

ng-init 函数在 tr 初始化时第一次调用.如果我单击更改按钮行集合被更改,它不会再次调用 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.

  1. 不跟踪,

在这种情况下,每当集合更新时,ngRepeat都会为集合中的数据项创建new uid.ngRepeat 看到 new uidsre-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其他人的渲染).(由于 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆