Angular: call function from view

Hi, I have the following problem:

In my opinion, I call the prepareDynamicData (itemMenu) function;

<div ng-repeat="itemMenu in menuDetailsData.categories" class="headDetails fontH2"> <div style="display: none">{{prepareDynamicData(itemMenu)}}</div> <a href="#" ng-show="dynamicData.expand">{{itemMenu.name}}</a> <div ng-repeat="cat in dynamicData.data"> <p>{{cat.name}}</p> <div class="articles"> <div ng-repeat="art in cat.items" class="article"> <div class="price"> <div></div> <span><i>β‚ͺ</i>{{art.price}}</span> </div> <div class="artDescr"> <span class="fontTitle">{{art.title}}</span> <p class="fontDetails">{{art.description}}</p> </div> </div> </div> </div> </div> 

I know that the top loop repeats only 2 times (this is verified), but the prepareDynamicData (itemMenu) function calls 4 times, I don’t know why !? Here is my controller:

 function MenuItemCtrl($scope, $routeParams, $http, $location, sharedData) { if (sharedData.getMenuDetails() == null) { $location.path('/menu'); return; } else { $scope.menu = sharedData.getMenu(); $scope.menuDetailsData = sharedData.getMenuDetailsData($routeParams.itemId); } $scope.dynamicData = { data : new Array(), expand : false }; $scope.prepareDynamicData = function (itemMenu) { if (itemMenu.items != null) { $scope.dynamicData.data[0] = itemMenu; $scope.dynamicData.expand = false; } else { $scope.dynamicData.data = itemMenu.categories; $scope.dynamicData.expand = true; } } 

}

Can you help me explain why this is happening! thanks

+6
source share
1 answer

Corner JS uses dirty tracking to ensure that viewing remains relevant. This means that AngularJS will evaluate the values ​​of your view bindings until they stabilize; thus, he will do this at least twice per binding at any time associated with the binding of the corresponding updates. (For example, if a particular element internal to the cycle has changed, it will most likely work two more times.) Therefore, it is necessary to ensure that the functions associated in the view do not have side effects and are quickly executed.

In general, porting data preparation tasks to code that starts when the controller boots up or to a service called from the controller is good practice - viewing linked code rarely has side effects! However, if you should / really want to call such a function from the view, just keep track of whether this function has already been called for this element.

The following is an additional read on dirty tracking in Angular, if you're interested .

+9
source

All Articles