简体   繁体   中英

is it possible using multiple controllers on one controller in angularjs?

so let say I have a multiple controller

angular.module('myApp.controllers', []).
              controller('MyCtrl1', ['$scope', function($scope) {
                  //define $scope.controller1 here
                  $scope.controller1 = "controller1";
              }).
              controller('MyCtrl1', ['$scope', function($scope) {
                  //define $scope.controller2 here
                  $scope.controller2 = "controller2";
              }).
              controller('MyCtrl3', ['$scope', function($scope) {
                  //I want to get the property of $scope.controller1 and    
                  //$scope.controller2 here
              });

as you can see above, for example I want to access $scope property from controller1 and controller2 from 3...

the question is, is angularjs capable of calling multiple controller on one controller ?

In AngularJS, scopes are inherited based on their position in the DOM. So if your html looked like:

<div ng-controller="my-ctrl1">
    <div ng-controller="my-ctrl2">
        <div ng-controller="my-ctrl3"></div>
    </div>
</div>

Then $scope.controller1 would be accessible from MyCtrl1, MyCtrl2, and MyCtrl3, but $scope.controller2 would only be available from MyCtrl2 and MyCtrl3.

If you want to share data between controllers, then you should store that data in a service and inject the service into the controllers:

angular.module('myApp.controllers', []).
    factory('MyData', function(){
        var MyData= {};
        return MyData;
    }).
    controller('MyCtrl1', ['$scope' 'MyData', function($scope, MyData) {
        MyData.controller1 = "controller1";
    }).
    controller('MyCtrl2', ['$scope', 'MyData', function($scope, MyData) {
        MyData.controller2 = "controller2";
    }).
    controller('MyCtrl3', ['$scope', 'MyData', function($scope, MyData) {
        // Now you can access MyData.controller1 and MyData.controller2
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM