Vandervals
Vandervals

Reputation: 6054

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:

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?

Upvotes: 6

Views: 4811

Answers (2)

BetaRide
BetaRide

Reputation: 16844

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.

Upvotes: 8

Duncan
Duncan

Reputation: 95652

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.

Upvotes: 2

Related Questions