Angular JS 中 ng-controller 值复制和引用复制

我们知道在使用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 

都是有同样的特性。

原文地址:https://www.cnblogs.com/Pikzas/p/8495482.html