Angular - Error: 10 $ digest () iterations. Aborting

I am trying to put a random integer in my ng-src path, for example:

<div ng-repeat="user in users"> <img ng-src="{{randomPicture()}}" alt=""> </div> 

And here is my main function in my controller:

 $scope.randomPicture = function(){ var PATH = 'assets/images/'; var image = Math.floor((Math.random() * 12) + 1); var ext = '.jpg'; var randomPic = PATH + image + ext; return randomPic; }; 

Images are displayed, but in the console I have this error:

 Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting! 

I found a lot of questions about this in stackoverflow, but I still cannot get rid of this error. Thank you for your help.

+5
source share
1 answer

Your binding will be random, it will be different every time Angular will observe the binding.

However, Angular stops the digest cycle when it reaches a stable state, when all observers return the same value twice in a row, which never happens to yours.

In short, you cannot bind a random value or anything that is always different in an Angular binding. You should create your image once and possibly re-randomize it based on some event.

 $scope.randomPicture = generateRandomPicture(); 

and

 <img ng-src="{{randomPicture}}"> 

UPDATE: And if you want to update the image every 3 seconds, for example, you can add

 // Generate a new random picture every 3 seconds $interval(function() { $scope.randomPicture = generateRandomPicture(); }, 3000); 

Update 2: Now that I have a better understanding of your problem, I suggest keeping everything as it is, but use :: , as shown below, if you use Angular 1.3 at least. Thus, you will have one random image created for each user, but generated only once.

In an earlier version of Angular or, alternatively, you can create an image of a determinist for a user who will feel random. for example, in your use of HTML:

 <img ng-src="{{randomPicture($index)}}"> 

And in your controller

 var rand1 = Math.round(Math.random()*10); var rand2 = Math.round(Math.random()*10); $scope.randomPicture = function(index) { var PATH = 'assets/images/'; var image = (index+rand1*rand2)%13 + 1; var ext = '.jpg'; var randomPic = PATH + image + ext; return randomPic; }; 


Note that if you use Angular 1.3+ and want to generate only once, you can use the ont-time binding using the syntax :: (using the same code for randomPicture ):
 <img ng-src="{{::randomPicture()}}"> 
+8
source

Source: https://habr.com/ru/post/1216185/


All Articles