Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use a function on angular ng-disabled?

Take this code:

var app = angular.module('test', []);

app.controller("controller", function() {
  this.hello = "Hello world";
  this.condition1 = true;
  this.condition2 = true;
  this.check_condition2 = function() {
    return this.condition2;
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="test" ng-controller="controller as ctrl">
  {{ctrl.hello}}
  <br>
  <label>
    <input type="checkbox" ng-model="ctrl.condition2">Condition2</label>
  <br>
  <button ng-disabled="ctrl.condition1 && ctrl.check_condition2()">My BTN</button>
</div>

I asume that angular works like this:

  • Angular whatches the controller's properties like condition1.

  • It reads the ng- directives and attaches the right ones to the properties. So if, for instance, ng-disabled depends on condition1, the directive is evaluated every time condition1 changes value.

Now take the sample above again. It is using 2 conditions but the second is not an attribute, it is a function. So how can Angular know that something that function is return changes?

One posibilty is that angular evaluates all its directives every time anything, related to them or not, changes on the model, but that doesn't sound very good for performance.

So, does anyone know how Angular whatches this ng-disabled expresion and wether I should use a function in that context or not?

like image 843
Vandervals Avatar asked Jun 03 '16 07:06

Vandervals


2 Answers

There's almost no difference. Angular adds a watch for everything you are using in your template. And it's evaluated on every digest cycle no matter wheter it's a variable or a function.

So the only overhead in your case is the call for a simple function.

Have a look at section 5.1 Scopes and the Digest Cycle of https://www.airpair.com/angularjs/posts/angularjs-performance-large-applications for how this works in angular.

like image 138
BetaRide Avatar answered Nov 14 '22 22:11

BetaRide


When angular is watching an expression that only contains simple values it can watch for any of the related variables to change. When it is watching an expression which includes a function call it calls the function on every digest loop.

It will usually be most efficient to simply update a flag every time it changes, however if you have a lot of places that the flag would need to be changed it can be cleaner code to just calculate the value inside a function and if the performance hit isn't large go for the cleaner code.

like image 29
Duncan Avatar answered Nov 14 '22 23:11

Duncan