以下用一個小範例說明 AngularJS 的作用域繼承行為,以及它在父子 controller 之間造成的同步問題。
<!doctype html>
<html ng-app="firstApp">
<head>
<meta charset="utf-8">
<script src="angular-1.3.0.js"></script>
</head>
<body>
<div ng-controller="parentCtrl">
<input ng-model="args">
<div ng-controller="childCtrl">
<input ng-model="args">
</div>
</div>
<script>
var app = angular.module('firstApp', []);
app.controller('parentCtrl', function($scope) {
$scope.args = '123';
}).controller('childCtrl', function($scope) {
});
</script>
</body>
</html>
childCtrl 裡完全沒有定義 args,但因為它的作用域原型繼承自 parentCtrl,所以能沿著原型鏈找到父作用域的 args,並把它渲染到 input 中。此時在父層 input 輸入內容,子層 input 會即時同步。
反方向卻不行。一旦你在子層 input 打字,父層的值不會改變,而且此後父層的變動也不再同步到子層。
原因在于:HTML 中的 ng-model 明確綁定在 childCtrl 的作用域上,因此 AngularJS 會為 childCtrl 建立一個屬於自己的 args 原始型別屬性。之後 childCtrl 在自己的作用域就能找到 args,不再向父層查找。最終父子各自擁有一份 args,兩邊的值也就永久失同步。
想避開這個特性,常見做法是不要把模型綁在原始型別上,而是綁到物件屬性(例如 ng-model="form.args")。物件只會有一個參考,子作用域修改的是同一個物件的屬性,父子自然同步。