-1

I am iterating over an array of 5 elements, and I call a function inside the ng-repeat.

$scope.myArray=[1,2,3,4,5]
var i=0;
$scope.diffHours= function(){
    i++;
    console.log(i)
    return "string";
}

<div ng-repeat="item in myArray">
  {{diffHours()}} 
</div>  

in the console it appears that this function is being called in total 40 times, when the array has only 5 elements, then this function should be used only 5 times in this case.

enter image description here

this is my code:

<script id="view.html" type="text/ng-template">
<ion-view view-title="Second page">
  <ion-content class="padding">
      <div ng-repeat="item in myArray">
         {{diffHours()}} 

      </div>            
  </ion-content>
</ion-view>

nameApp.controller('ViewCtrl', function($scope, $stateParams, $ionicHistory) 
{
  $scope.myArray=[1,2,3,4,5]
  var i=0;
  $scope.diffHours= function(){
      i++;
      console.log(i)
      return "string";
  }
});

I have a real example where I have a series of more complex operations and libraries that I could not include. but this small example helps me explain my problem.

What am I doing wrong?

Link updated:

https://plnkr.co/edit/e8Jfu000vbvnGS9QfnWQ?p=preview

halfer
  • 19,824
  • 17
  • 99
  • 186
yavg
  • 2,761
  • 7
  • 45
  • 115

1 Answers1

0

Angular has a digest cycle due to $scope, so anytime you change $scope it will rerun everything, since you are using a function it will call the function again to get new values hence there will be performance glitch. Try to refrain from creating any new key in $scope , create var variables. offcourse you need to create $scope variable for binding it to html :)

nameApp.controller('ViewCtrl', function($scope, $stateParams, $ionicHistory) {
  var myArray = [1, 2, 3, 4, 5],
    diffArray = [];
    var i = 0;
    var diffHours = function() {
      i++;
      console.log(i)
      return "string";
    }

  myArray.forEach(function(item) {
    diffArray.push(diffHours(item))
  })
  $scope.diffArray = angular.copy(diffArray);

});

Also you can use track by and give some unique value , i have given index here but it will depend on the data you get .

 <div ng-repeat="item in diffArray track by $index">
         {{item}} 

      </div>    

Hope this answers your query , good luck !

Atul
  • 420
  • 2
  • 10