$范围和$ rootscope混乱 [英] $scope and $rootscope confusion
问题描述
我不明白为什么这个程序的输出并不是
I don't understand why the output of this program is not
Global value is 4
Child Instance of Function1 created :- 1
Child Instance of Function2 created :- 2
Child Instance of Function1 created :- 3
Child Instance of Function2 created :- 4
Plunker - http://plnkr.co/edit/HktvgxMM0g1WJG2oLjIN?p=preVIEW
感谢您的帮助。
推荐答案
您可以用这种方式$ rootScope明白这是最上面的范围,所有其他范围(即$范围内)来这里面。所以,柜面你必须通过范围之间的值,那么你必须使用$ rootScope。
You can understand it in this way $rootScope is top most scope and all the other scope (i.e. $scope) comes inside this. So incase you have to pass value between scope then you have to use $rootScope.
请注意:功能1使用局部变量柜台里范围在控制器内。即每个控制器,有自己的范围。功能2使用全局变量计数器,因为没有全局变量定义。
Note: function1 use local variable Counter where scope is within the controller. I.e. each controller have there own scope. function2 use global variable Counter, because no global variable define.
在你的情况下,(记住角度支持双向绑定,所以每当全球价值改变它在所有的地方的变化),控制器被调用的顺序如下功能1 - >功能2 - >功能1 - >功能2
In your case the (remember angular support two way binding, so whenever global value change it changes at all the places), The controllers get called in following order function1 -> function2 -> function1 -> function2.
在功能1
获得所谓的第一次 $ rootScope.Counter
不是present所以它具有一个初始化和分配相同的局部变量计数器。
When function1
get called first time $rootScope.Counter
is not present so it initialize with one and assign the same to local variable 'Counter'.
so output look like
Global value is 1
Child Instance of Function1 created :- 1
Child Instance of Function2 created :- 1
Child Instance of Function1 created :- NA // local scope for this is not created
Child Instance of Function2 created :- 1
现在函数2将被调用。这种增加全局变量计数器为2,并用它来显示
Now function2 will get called. This increase global variable Counter to 2 and use it to display
so output look like
Global value is 2
Child Instance of Function1 created :- 1
Child Instance of Function2 created :- 2
Child Instance of Function1 created :- NA // local scope for this is not created
Child Instance of Function2 created :- 2
现在FUNCTION1将再次调用。这一增长全局变量计数为3,并为其分配局部变量。
Now function1 will get called again. This increase global variable Counter to 3 and assign it local variable.
so output look like
Global value is 3
Child Instance of Function1 created :- 1
Child Instance of Function2 created :- 3
Child Instance of Function1 created :- 3 //Because rootScope already have counter variable with 2
Child Instance of Function2 created :- 3
终于函数2再次调用,这增加了全局变量计数为4,并用它来显示
and finally function2 get called again, This increase global variable Counter to 4 and use it to display
so output look like
Global value is 4
Child Instance of Function1 created :- 1
Child Instance of Function2 created :- 4
Child Instance of Function1 created :- 3
Child Instance of Function2 created :- 4
这篇关于$范围和$ rootscope混乱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!