Why $ rootScope. Does $ Watch return a value several times?

I have an angular application that has a controller with a function that monitors a variable when it changes in the root directory; i.e

angular.module('myApp').controller('myController', function($scope, $rootScope) { $rootScope.$watch('someVar', function() { console.log($rootScope.someVar); }); } 

For some reason, if I change $ rootScope.someVar to "Hello", I get the following console output

 > Hello > Hello > Hello 

Why is he doing this? I am writing a program that analyzes large data files, and if I could increase productivity three times, my life would be much happier.

+4
source share
2 answers

If a side effect of the clock causes a change in the variable, the clock is called again until all changes are eliminated.

So, if the action that triggers the clock (the action that changes someVar) leads to other actions that also update someVar, there could be a cascade (up to 10 times before angular says enough?)

+2
source

I had a similar problem watching a variable in $ rootScope from a child controller and "opening" this controller more times. Each time I open the controller, it seems that angular adds another observer, and when the variable changes, the observer fires more times.

I solved this problem by adding an observer and broadcasting a custom event to the parent controller (AppCtrl), and on the child controller (ChildCtrl) that listened for this event:

AppCtrl:

 $rootScope.$watch('myVar', function(myVar){ if(myVar){ var obj = doSomethingWithMyVar(myVar); $scope.$broadcast('myEventName', obj); } }); 

ChildCtrl:

 $scope.$on('myEventName', function(event, obj){ console.log(obj); }); 
0
source

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


All Articles