AngularJS 作用域里的值复制和引用复制

对象要么是值复制要么是引用复制。字符串、数字和布尔型变量是值

复制。数组、对象和函数则是引用复制。

1.值复制:

<!doctype html>
<html ng-app="myApp">
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0-rc.3/angular.js"></script>
</head>
<body>
<div ng-controller="SomeController">
    {{ someBareValue }}
    <button ng-click="someAction()">Communicate to child</button>
    <div ng-controller="ChildController">
        {{ someBareValue }}
        <button ng-click="childAction()">Communicate to parent</button>
    </div>
</div>
    <script>
        angular.module('myApp', [])
        .controller('SomeController', function ($scope) {
            // 反模式,裸值
            $scope.someBareValue = 'hello computer';
            // 设置 $scope 本身的操作,这样没问题
            $scope.someAction = function () {
                // 在SomeController和ChildController中设置{{ someBareValue }}
                $scope.someBareValue = 'hello human, from parent';
            };
        })
        .controller('ChildController', function ($scope) {
            $scope.childAction = function () {
                // 在ChildController中设置{{ someBareValue }}
                $scope.someBareValue = 'hello human, from child';
            };
        });
    </script>
</body>
</html>

 2.引用复制:

<!doctype html>
<html ng-app="myApp">
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0-rc.3/angular.js"></script>
</head>
<body>

    <div ng-controller="SomeCtrl">
        {{ someModel.someValue }}
        <button ng-click="someAction()">Communicate to child</button>
        <div ng-controller="ChildCtrl">
            {{ someModel.someValue }}
            <button ng-click="childAction()">Communicate to parent</button>
        </div>
    </div>

    <script>
        angular.module('myApp', [])
        .controller('SomeCtrl', function ($scope) {
            // best practice, always use a model
            $scope.someModel = {
                someValue: 'hello computer'
            }
            $scope.someAction = function () {
                $scope.someModel.someValue = 'hello human, from parent';
            };
        })
        .controller('ChildCtrl', function ($scope) {
            $scope.childAction = function () {
                $scope.someModel.someValue = 'hello human, from child';
            };
        });
    </script>

</body>
</html>

 

posted @ 2015-10-03 09:28  Byron12345  阅读(285)  评论(0编辑  收藏  举报