I've been learning AngularJs and have built a very basic Angular app. In one part of the app, I've used ngClass at a div element like
<div ng-class='{"some class": aFuncTruthyOrFalsy()}'>
<!-- aFuncTruthyOrFalsy() is defined in the controller for this view-->
Now, there's an input element in the view that is non-related to the above element and does not relate at all to any of the values checked in the function above.
I noticed that every whenever I type something in the input field (change event, keypressed event) it causes a re-evaluation of the ngClass. (I've put in a console log inside the aFuncTruthyOrFalsy function). I'm not able to determine which all events are bubbling to cause the reevaluation.
It seems to me that ngClass reevaluates at every single event in the page.
Can anyone please explain/elaborate this behavior?
Is it possible to cache the evaluated class at the initial load of the view?
What if there are multiple ngClass being used in the same view and each of the expression evaluation is delegated to some function that again does some multiple operation to come to get the evaluated expression?
Angular binding is using $watch to monitor changes in the function value. The digest cycle is calling your function to compare the result with last value.
This article is nice explaining this http://tutorials.jenkov.com/angularjs/watch-digest-apply.html#watch
I suggest binding to scope variables instead of functions. i.e. have a variable in the scope that will store result of that function, and you update that whenever required.
after all you don't want to call methods from your view probably.Your current setup leaves the door open to make the whole MVC concept void,e.g. someone later add functionality inside that method that was supposed to be just a getter.