AngularJS access controller $scope from outside

前端 未结 1 743
误落风尘
误落风尘 2020-12-02 12:35
var theApp = angular.module(\'theApp\', []);
var app = angular.module(\'theApp\', [\'ui.bootstrap\']);
app.controller(\'MenuSideController\', [\'$scope\',\'SnazzySer         


        
相关标签:
1条回答
  • 2020-12-02 12:52

    Without seeing the markup, I guess the scope of MenuSideController is a child scope to the scope you are selecting.

    While it is possible to traverse down the tree like this (assuming the scope we want is the first child):

    var appElement = document.querySelector('[ng-app=theApp]');
    var appScope = angular.element(appElement).scope();
    var controllerScope = appScope.$$childHead;
    console.log(controllerScope.user);
    

    It is simpler to just select the element where the specific controller is attached.

    Assuming you are using the ng-controller directive:

    <body ng-controller="MenuSideController"></body>
    

    Do instead:

    var controllerElement = document.querySelector('body');
    var controllerScope = angular.element(controllerElement).scope();
    console.log(controllerScope.user);
    

    Demo: http://plnkr.co/edit/WVNDG9sgYgoWaNlrNCVC?p=preview

    angular.element(document).ready(function() {
    
      var appElement = document.querySelector('[ng-app=theApp]');
      var appScope = angular.element(appElement).scope();
    
      console.log('Traversing from appScope to controllerScope:', appScope.$$childHead.user);
    
    
      var controllerElement = document.querySelector('body');
      var controllerScope = angular.element(controllerElement).scope();
    
      console.log('Directly from controllerScope:', controllerScope.user);
    
    
      controllerScope.$apply(function() {
        controllerScope.user.zoomlvl = '10';
      });
    });
    
    0 讨论(0)
提交回复
热议问题