Angular JS 中 ng-controller 值復制和引用復制
阿新 • • 發佈:2018-03-03
span tro strong bar del ng- scope value 變化
我們知道在使用ng-app或者ng-controller指令的時候,都會創建一個新的作用域($rootScope或者是$scope),並且在使用ng-controller指令創建的作用域會繼承父級作用域($rootScope或者是$scope)所有的方法和屬性。
但是這裏繼承的屬性就有一些學問了
運行如下代碼:
html
<div ng-controller="SomeController"> {{ someBareValue }} <button ng-click="someAction()">Parent button</button> <div ng-controller="ChildController"> {{ someBareValue }} <button ng-click="childAction()">Child button</button> </div> </div>
js
angular.module(‘myApp‘, []) .controller(‘SomeController‘, function($scope) { $scope.someBareValue = ‘hello computer‘; $scope.someAction = function() { $scope.someBareValue = ‘hello human, from parent‘; }; }) .controller(‘ChildController‘, function($scope) { $scope.childAction = function() { $scope.someBareValue = ‘hello human, from child‘; }; });
初始加載完,父子作用域顯示同樣的值
當點擊Parent button的時候,可以看到父子作用域同時變化
然後點擊Child button的時候,子作用域的值更新了
而後再次點擊Parent button的時候,發現父作用域更新了,但是子作用域卻不在變化。
這是因為,父子作用域間的繼承是通過的是一個 字符串 數字或者布爾值來實現的,這就是JS的值復制。
再運行如下代碼:
html
<div ng-controller="SomeController"> {{ someModel.someValue }} <button ng-click="someAction()">Parent button</button> <div ng-controller="ChildController"> {{ someModel.someValue }} <button ng-click="childAction()">Child Button</button> </div> </div>
js
angular.module(‘myApp‘, []) .controller(‘SomeController‘, function($scope) { $scope.someModel = { someValue: ‘hello computer‘ } $scope.someAction = function() { $scope.someModel.someValue = ‘hello human, from parent‘; }; }) .controller(‘ChildController‘, function($scope) { $scope.childAction = function() { $scope.someModel.someValue = ‘hello human, from child‘; }; });
可以看到這個例子和上面例子的區別主要在於,子作用域繼承自父作用域是通過一個對象someModel實現的,運行該例子。
初始完成之後,父子作用域顯示相同字符串。
然後無論點擊Parent Button 還是Child Button,父子作用域都同步顯示相同的字符串。
這是因為,父子作用域間的繼承是通過的是一個 對象 來實現的,這就是JS的引用復制。
此外,除了ng-controller之外
ng-include
ng-switch
ng-repeat
ng-view
ng-if
都是有同樣的特性。
Angular JS 中 ng-controller 值復制和引用復制