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.
When you use
track by $index
. Watch is kept ondata item
incollection
by theirindex
and not byuid
.not track by
,In this case,
ngRepeat
createnew uid
fordata item
in collection whenevercollection is updated
.ngRepeat
seesnew uids
andre-renders
all elements.track by,($index)
In this case,
ngRepeat
usesindex as uid
for data item in collection.ngRepeat
doesn't see anynew uids
and henceno re-rendering
of elements (add or remove,if any, butno rendering of others
). (Aswatch
is kept on data, it will getupdated
but no-rendering)