Ilia Barahovsky
Ilia Barahovsky

Reputation: 10498

Angular: scope variable vs function

What is better in Angular - to bind to a variable or to a function. In particular:

Example for two options:

<!-- With function -->
<button ng-disabled="noDataFoo()">Add</button>

<!-- With variable -->
<button ng-disabled="noDataFlag">Add</button>

Backing controller:

app.controller('sample', function($scope, $http) {
    $scope.noDataFlag = true;

    $scope.noDataFoo = function () {
        return !$scope.data;
    };

    $http('/api/getdata').success(function(data) {
        $scope.data = data;
        $scope.noDataFlag = false;
    };
});

Upvotes: 7

Views: 1644

Answers (2)

Ilia Barahovsky
Ilia Barahovsky

Reputation: 10498

I made some tests and counted how many times the function is called under different circumstances. It occurs, the function is called the number of times it has binding, sometimes twice the number and it seems to happen after each external activity, like page reload or button click or AJAX call.

In simple words, if you have <button ng-disabled="noDataFoo()"> and then {{noDataFoo()}} in HTML, the function will be called 4 times at page load, then another 2 or 4 times if some $http service brings data, and another 2 or 4 times if some other button was clicked. From experiments, the number is 2 if noDataFoo doesn't change and 4 if it does change. By the way, the same holds for clicks on another controller.

My conclusion is: it's OK to bind to quick functions. For longer ones it's better to keep number of bindings small. And for even longer ones it's wiser to cache the result and handle "manually" cache updates.

Upvotes: 2

Joe
Joe

Reputation: 2596

I'm not a javascript performance expert or anything, but my naive opinion would be that the variable would out perform the function by MAYBE a couple of nanoseconds because it's a 2 step process.

Also, the example above would be just as easily accomplished using:

<button ng-disabled="!data">Add</button>

Upvotes: 2

Related Questions