AngularJS access parent scope from child controller

前端 未结 9 1916
南方客
南方客 2020-11-22 07:30

I\'ve set up my controllers using data-ng-controller=\"xyzController as vm\"

I have a scenario with parent / child nested controllers. I have no problem

9条回答
  •  庸人自扰
    2020-11-22 08:01

    You can also circumvent scope inheritance and store things in the "global" scope.

    If you have a main controller in your application which wraps all other controllers, you can install a "hook" to the global scope:

    function RootCtrl($scope) {
        $scope.root = $scope;
    }
    

    Then in any child controller, you can access the "global" scope with $scope.root. Anything you set here will be globally visible.

    Example:

    function RootCtrl($scope) {
      $scope.root = $scope;
    }
    
    function ChildCtrl($scope) {
      $scope.setValue = function() {
        $scope.root.someGlobalVar = 'someVal';
      }
    }
    
    function OtherChildCtrl($scope) {
    }
    
    
    

    someGlobalVar value: {{someGlobalVar}}

提交回复
热议问题