使用$ index进行跟踪时,ng-init没有第二次调用 [英] ng-init is not calling second time when track by $index used

查看:80
本文介绍了使用$ 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();
});

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.

  1. not track by

在这种情况下,ngRepeat每当collection is updated时在集合中为data item创建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)

在这种情况下,ngRepeatindex 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屋!

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