Angular: scope vs function variable

Which is better in Angular - for binding to a variable or to a function. In particular:

  • Is there any performance limitation due to the digest or extra hours created for the function?
  • Are there any recommendations as to which function functions should and should not do?

An example for two parameters:

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

Backup 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; }; }); 
+6
source share
2 answers

I did some tests and calculated how many times the function is called in different circumstances. This happens, the function is called the number of times it has a binding , sometimes twice as many, and it seems that after each external activity , for example, reloading a page or pressing a button or AJAX.

In simple words, if you have <button ng-disabled="noDataFoo()"> and then {{noDataFoo()}} in HTML, the function will be called 4 times when the page loads, then another 2 or 4 times, if any Either the $http service brings data, and the other 2 or 4 times if another button is pressed. From experiments, the number is 2 if noDataFoo does not change and 4 if it changes. By the way, the same applies to clicks on another controller.

My conclusion : it is normal to get attached to fast functions. For longer ones, it is better to keep the number of bindings small. And even for longer ones, it is more reasonable to cache the result and process the cache updates manually.

+2
source

I am not an expert on javascript performance or anything else, but my naive opinion would be that the variable will perform the MAYBE function for a couple of nanoseconds, because it is a two-step process.

In addition, the above example would be just as easy to execute using:

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

Source: https://habr.com/ru/post/970540/


All Articles