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;
};
});
Local scope just refers to the scope available to a given variable, but function scope would refer to variables inside a function. Here var x is inside a function, so it's only accessible inside the function.
AngularJS Scope The scope is the binding part between the HTML (view) and the JavaScript (controller). The scope is an object with the available properties and methods. The scope is available for both the view and the controller.
"$rootScope” is a parent object of all “$scope” angular objects created in a web page. $scope is created with ng-controller while $rootscope is created with ng-app . Follow this answer to receive notifications.
In short, in case of dependency injection the scope object is received as $scope while in case of non-dependency injection scope object is received as scope or with any name. Save this answer.
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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With