在我AngularJS應用程序,我有2個控制器未嵌套。調用$ scope。$ apply方法似乎也會影響另一個同級作用域。
在下面的jsfiddle中,無論何時ControllerTwo每秒更新一次時鐘,ControllerOne的{{doubleMe(x)}}表達式都會被評估。這可以從控制檯消息中顯示。
我可以理解爲什麼那個表達式求值,每當文本輸入(在相同的範圍內)的變化,但爲什麼$範圍。$另一個範圍適用因爲那expression要重新評估呢?
注意,我可能避免$範圍。$使用$超時申請,但觀察到的結果。
<!-- HTML file -->
<div ng-app>
<h1>Root</h1>
<div ng-controller="ControllerOne">
<h2>Scope One</h2>
1 * 2 = {{doubleMe(1)}}<br/>
2 * 2 = {{doubleMe(2)}}<br/>
3 * 2 = {{doubleMe(3)}}<br/>
<input ng-model="text">
</div>
<div ng-controller="ControllerTwo">
<h2>Scope Two</h2>
{{clock.now | date:'yyyy-MM-dd HH:mm:ss'}}
</div>
</div>
// js文件
function ControllerOne($scope) {
var counter=1;
$scope.doubleMe = function(input) {
console.log(counter++);
return input*2;
}
$scope.text = "Change Me";
}
function ControllerTwo($scope) {
$scope.clock = {
now: new Date()
};
var updateClock = function() {
$scope.clock.now = new Date()
};
setInterval(function() {
$scope.$apply(updateClock);
}, 1000);
}
或許更何況它並不總是最好使用$消化它是非常重要的。例如,考慮$摘要()的範圍內是要升級的變化,以更高的範圍的NG-repeat的範圍一個孩子正在發生的事情。它是真正的$摘要性能更好但超過$應用它是不是 –