ng-class="callToFunc()" - ran crazy amount of times?

7,194 views
Skip to first unread message

Olivier Clément

unread,
Feb 11, 2013, 3:09:23 PM2/11/13
to ang...@googlegroups.com
All, I just noticed and tried searching about this and didn't find any relevant info so here goes:

I noticed this in a quite complex app, and thinking I caused this somehow I tried to replicate it in a very basic angular app:

Long story short: ng-class calls a function, that returns a string.
Turns out the function is being called (in my case) 12 times.

Anyone can chime on this? Should we worry about this or anything, what about performance loss, implications of this?

Thanks

clayton collie

unread,
Feb 11, 2013, 3:29:11 PM2/11/13
to ang...@googlegroups.com
Expected. Angular uses dirty checking to ensure binding stays in sync, so there is at minimum 2 calls per digest. The maximum depends on how many cascades happen because of dependencies.
The suggestion is to make scope functions fast and idempotent.

clayton collie

unread,
Feb 11, 2013, 3:33:04 PM2/11/13
to ang...@googlegroups.com
Looking at your code though, 12 does seem a bit high..

clayton collie

unread,
Feb 11, 2013, 3:41:23 PM2/11/13
to ang...@googlegroups.com
I see the issue. Angular uses dirty checking, so during a digest it iterates until no changes are detected in watched items. Your getClass() method mutates on each call, so angular has  iterates until it reaches its internal threshold and quits.
It's a true Heisenbug :-)

Olivier Clément

unread,
Feb 11, 2013, 3:45:46 PM2/11/13
to ang...@googlegroups.com
Copy that, thanks for the explanation

Peter Bacon Darwin

unread,
Feb 12, 2013, 5:35:59 AM2/12/13
to ang...@googlegroups.com
So the answer is not to do lots of work in functions that will be called by the dirty checking mechanism.  Instead $watch the dependencies and compute callToFunc() only once per change and store this in the scope to be picked up by the ng-class directive.


--
You received this message because you are subscribed to the Google Groups "AngularJS" group.
To unsubscribe from this group and stop receiving emails from it, send an email to angular+u...@googlegroups.com.
To post to this group, send email to ang...@googlegroups.com.
Visit this group at http://groups.google.com/group/angular?hl=en-US.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

Olivier Clément

unread,
Feb 13, 2013, 2:40:52 PM2/13/13
to ang...@googlegroups.com
Sounds good, thanks for your reply and example;
I'll refactor my code to follow your example
Reply all
Reply to author
Forward
0 new messages