3

I have this simple controller markup

<div ng-controller="TestCtrl" ng-show="isVisible()">
    <input type="text" ng-model="smth"/><br>
    <span>{{smth}}</span>
</div> 

And controller itself

function TestCtrl($scope, $log)
{
    $scope.smth = 'smth';

    $scope.isVisible = function(){
        $log.log('isVisible is running');

        return true;
    }
}

Why after every little change of model (e.g. changing one letter inside textbox) I can see isVisible is running in console? It's not problem for such case but I think it will be in large application. Can I avoid this?

Stewie
  • 60,366
  • 20
  • 146
  • 113
Vitalii Korsakov
  • 45,737
  • 20
  • 72
  • 90
  • It's because it's a function so angular during a $digest phase needs to run it to see if it has changed – Liviu T. Mar 03 '13 at 19:31

2 Answers2

5

Liviu T. is right. You can't avoid having your isVisible function executed on every scope change. If Angular didn't rerun this function, than it could get out of sync with the rest of the code (for example if it was using $scope.smth model to resolve the return value).

Having this in mind, you should always try to make your functions idempotent/pure (always returns the same output given the same input) and light, because directive such as ng-hide, ng-show, ng-class and similar will always re-evaluate the expression assigned to them, on every $digest cycle.

Now, if you really don't want it to execute all over again, you might try some of the memoization techniques for caching the function output.

Stewie
  • 60,366
  • 20
  • 146
  • 113
  • It is as much about being idempotent here (which is important property in expressions as it will prevent errors due to model not stabilizing) as about the fact that those expressions should evaluate _fast_. – pkozlowski.opensource Mar 04 '13 at 18:11
3

This is normal as this is essential pat of how AngularJS does its "magic". This answer has more details: https://stackoverflow.com/a/9693933/1418796

There are different techniques to make sure that you don't run into performance problems but no, in general you can't exclude those expressions from being evaluated.

Community
  • 1
  • 1
pkozlowski.opensource
  • 117,202
  • 60
  • 326
  • 286