Angulars Controller作用域继承

Angulars Controller作用域继承

1,裸值,是复制而非引用


<html>
    <head>
        <meta charset="UTF-8">
        <title>dasdtitle>
        <script src="angular-1.0.1.min.js">script>
    head>
    <body ng-app='myApp'>
        <div ng-controller="SomeController">
            {{ someBareValue }}
            <button ng-click="someAction()">Communicate to childbutton>
            <div ng-controller="ChildController">
                {{ someBareValue }}
                <button ng-click="childAction()">Communicate to parentbutton>
            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>

先点击childbutton,parentbutton不改变,则表示子作用域对父作用域的$scope引用只是值得复制而非引用。

2.对象属性,是引用而非复制
如果将模型对象的某个属性设置为字符串,它会通过引用进行共享,因此在子 scope scope中的这个属性。下面的例子展示了正确的做法:


<html>
    <head>
        <meta charset="UTF-8">
        <title>dasdtitle>
        <script src="angular-1.0.1.min.js">script>
    head>
    <body ng-app='myApp'>
        <div ng-controller="SomeController">
            {{ someModel.someValue }}
            <button ng-click="someAction()">Communicate to childbutton>
            <div ng-controller="ChildController">
                {{ someModel.someValue }}
                <button ng-click="childAction()">Communicate to parentbutton>
            div>
        div>
        <script>
            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';
                    };
                });
        script>
    body>
html>

无论点击哪个按钮,值都会进行同步修改。

你可能感兴趣的:(angularjs)