ng-init is not calling second time when track by $index used

人盡茶涼 提交于 2019-12-24 07:19:10

问题


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"/>

controller:

$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 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.


回答1:


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,

    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.

  2. track by,($index)

    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)



来源:https://stackoverflow.com/questions/39976896/ng-init-is-not-calling-second-time-when-track-by-index-used

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!