我有下面的代碼
提琴手Link
HTML中的$範圍:
<div ng-app ng-controller="ParentCtrl" ng-init="cities='North America'">
<div ng-controller="ChildCtrl as vm">
{{$parent.cities}}
<div>
<button ng-click="check()">Check the value</button>
</div>
</div>
</div>
Javascript:
function ParentCtrl($scope, $rootScope) {
$rootScope.$watch('changecity', function() {
$scope.cities = "South America";
console.log("changed the city");
});
$scope.cities = "North America";
}
function ChildCtrl($scope, $rootScope) {
$scope.check = function(){
console.log("$parent value:"+$scope.$parent.cities + "\n$scope value:"+$scope.cities)
};
}
我有ng-init = "cities='North America'"
和$scope.cities = "North America";
在ParentCtrl
。
但輸出的視圖更新爲南美洲這很奇怪。有人可以解釋在上述代碼塊中發生的執行的全部基礎。
- 是
$watch
最初執行回調嗎? - 作用域覆蓋的優先級是什麼?即:監視回調中的作用域覆蓋之前設置的值?
不要使用'NG-init'用於這一目的。在控制器中聲明變量 – charlietfl