简体   繁体   中英

ng-repeat loop more than the number of elements

I am trying to implement ng-repeat with ng-style . It works perfectly. However, I do not understand why my method is called more than the number of elements in my ng-repeat !

Do you know why?

To complete my explanation, I created a : JSFiddle

I think that when your html code is compiled, it executes ng-style directive even if there is no data (when items == null). After that your controller changes $scope.items, forcing other calls to $scope.getStyle().

I think if you put a ng-if="items != null" within ng-repeat, your function will be called only 5 times.

Solution looks fine. The reason for multiple calls is angular digest loop. You can read about it here: http://www.benlesh.com/2013/08/angularjs-watch-digest-and-apply-oh-my.html

It works by running the loop and looking if the values changed for the watches. When they stabilize it ends. You can have multiple passes of the event loop in angular app and that is pretty normal. The limit is set afaik for 10 iterations. If bindings do not stabilize then exception is thrown.

Additional reading, highly recommended: http://teropa.info/blog/2013/11/03/make-your-own-angular-part-1-scopes-and-digest.html Part Keep Digesting While Dirty is the answer to your question i believe.

So it is by design.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM