在AngularJS中使用嵌套控制器时,$ scope对象是否在所有控制器之间共享

时间:2017-08-31 09:59:48

标签: javascript angularjs

我们可以在AngularJS中使用嵌套控制器吗?对于嵌套控制器,$ scope对象是否在所有控制器之间共享。

问题是: -

我可以在所有控制器上访问第一个控制器$ scope值,但是我无法在第三个控制器中获取第二个控制器范围对象。您可以在下面的代码段中运行并检查它。



 var app = angular.module("appTest",[]);


    function Controller1($scope) {
      $scope.text1= "text Sample 1"
    }

    function Controller2($scope) {
      $scope.text2= "text sample 2"
    }
    
    function Controller3($scope) {
      $scope.text3 = $scope.text1 + " And " + $scope.text2;
    }

    app.controller("Controller1",Controller1);
    app.controller("Controller2",Controller2);
    app.controller("Controller3",Controller3);

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="appTest">
    <div ng-controller="Controller1">
      <div>
      <h1> First Controller</h1>
        First Controller Values is <b> {{text1}}</b>
      </div>
      <div ng-controller="Controller2">
       <h1> Second  Controller</h1>
        First Controller Values is <b> {{text1}}</b>
        <br />
        Second controller value is <b> {{text2}}</b>
      </div>
       <div ng-controller="Controller3">
       <h1> Thired  Controller</h1>
        First Controller Values + Second controller value  is <b> {{text3}}</b>
       
      </div>
    </div>
  </body>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:2)

是的,您可以在angularjs中使用嵌套控制器。父控制器范围将在原型链中继承,并且所有子控制器都可以访问父范围。

  

但是我无法在第三个控制器中获得第二个控制器范围对象。

原因是您的第三个控制器独立于您的第二个控制器。您无法直接从另一个独立控制器访问$scope属性。您可以将第三个控制器嵌套在第二个控制器中,也可以使用服务来共享数据(后者更为首选)。

&#13;
&#13;
var app = angular.module("appTest",[]);


    function Controller1($scope) {
      $scope.text1= "text Sample 1"
    }

    function Controller2($scope) {
      $scope.text2= "text sample 2"
      $scope.text1="text Sample 1 from controller 2";//this will be printed in controller 2 and if you want to access parent data, use $parent
    }
    
    function Controller3($scope) {
      $scope.text3 = $scope.text1 + " And " + $scope.text2;
    }

    app.controller("Controller1",Controller1);
    app.controller("Controller2",Controller2);
    app.controller("Controller3",Controller3);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-app="appTest">
    <div ng-controller="Controller1">
        <div>
            <h1> First Controller</h1> First Controller Values is <b> {{text1}}</b> </div>
        <div ng-controller="Controller2">
            <h1> Second  Controller</h1> First Controller Values is <b> {{$parent.text1}}</b>
             First Controller's scope objects value in scond controller <b> {{text1}}</b>
            <br /> Second controller value is <b> {{text2}}</b>
            <div ng-controller="Controller3">
                <h1> Thired  Controller</h1> First Controller Values + Second controller value is <b> {{text3}}</b> </div>
        </div>
    </div>
</body>
&#13;
&#13;
&#13;