7

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

  • Is there any performance penalty due to digest calls or additional watches that are created for a function?
  • Are there any recommendations for what scope functions should and shouldn't do?

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;
    };
});

2 Answers 2

2

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>
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much for your answer. I see that I haven't fully explained my intentions. My concern is - how often Angular computes the function. Probably there exist Angular recommendation for not binding to functions. The example in question is simplified, in application function is longer and it depends on return value from several APIs. Which makes status variable difficult to manage...
2

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.

1 Comment

This is old but I point out that scope variable should be the first choice for some of the reasons you stated.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.