var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope, $interval) {
var counter = false;
var responseMock = [
[
{_id: 1, name: 'Josh'},
{_id: 2, name: 'Joseph'},
{_id: 3, name: 'Kevin'}
],
[
{_id: 1, name: 'Michael'},
{_id: 2, name: 'Frank'},
{_id: 3, name: 'Lian'}
]
];
var getItems = function() {
if (counter === false) {
counter = true;
return responseMock[0];
}
counter = false;
return responseMock[1];
};
var itemsMock = getItems();
$scope.items = itemsMock;
$scope.i = itemsMock;
$interval(function() {
itemsMock = getItems();
$scope.items = itemsMock;
$scope.i = itemsMock;
}, 5000);
});
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js@1.5.8" src="https://code.angularjs.org/1.5.8/angular.min.js" data-semver="1.5.8"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<h1>Inspect the elements in the ngRepeat</h1>
<p>If you like to take a look in this implementation using Angular 2, please <a href="http://embed.plnkr.co/oi0OIzoJA9o6ppiMEjQM/">Take a look in this example</a></p>
<h2>Without track by</h2>
<p>In the first loop, the elements will be removed from the DOM</p>
<div ng-repeat="item in items">
{{ item.name }}
</div>
<br/><br/>
<h2>With track by</h2>
<p>But in the second loop, the elements stay in DOM.
The difference is totally about the approach.</p>
<p>If you are not using `track by`, your angular App creates the `$$hashKey`
property for you and when you update the information you are creating a new
element instead update the data.
</p>
<p>For more details please <a href="https://docs.angularjs.org/api/ng/directive/ngRepeat#tracking-and-duplicates">Visit the `ngRepeat` "Tracking and Duplicates" topic</a> in documentation.</p>
<div ng-repeat="a in i track by a._id">
{{ a.name }}
</div>
</body>
</html>
/* Put your css in here */