Angular v1.4 repeat a div without re-rendering already rendered items

97 Views Asked by At

I wrote code to repeat an image array and a load more button to ajax request and push response images in that array. But every time new response comes then whole images reshuffled.

<div class="container">
    <div ng-repeat="image in images track by $index">
        <div class="panel panel-default">
           <div>
             <img ng-src="{{image.Src}}" alt="" height="200" width="200">
          </div>
       </div>
   </div>
</div>

And in my controller code:

$scope.loadMore = function () {
     pageNumber ++;
     homeService.getListData(pageNumber)
                           .then(function (data) {
                               for (var i = 0; i < data.length; i++) {
                                   $scope.images.push(data[i]);
                               };
                        });
                    };
                };

every time server send three images. Previously I didn't use track by $index then from from this SO answar I added track by $index but no luck.

I think angular is re-rendering the whole array. If so, how can I stop this re-rendering?

2

There are 2 best solutions below

0
On

You could use Array.concat() instead of pushing all the elements, this might solve your problem.

    $scope.loadMore = function () {
         pageNumber ++;
         homeService.getListData(pageNumber)
               .then(function (data) {
                  $scope.images = $scope.images.concat(data);
               });
    };
0
On

It's hard to say why angular is reordering your images since it does not look like your array is being reordered.

Try adding an orderBy clause. Something like this should work:

<div ng-repeat="image in images  | orderBy : image.$index track by $index">

And keep everything else the same. This will ensure that the order of your images stays consistent.