AngularJS从外部访问控制器$ scope

ngp*_*und 43 angularjs angularjs-scope

var theApp = angular.module('theApp', []);
var app = angular.module('theApp', ['ui.bootstrap']);
app.controller('MenuSideController', ['$scope','SnazzyService','$modal','$log', function($scope, SnazzyService, $modal, $log) {
    $scope.user.zoomlvl = '2';
}]);
Run Code Online (Sandbox Code Playgroud)

我有上面的控制器,它设置了一个$scope我只能从内部访问值.

但我看到的地方,使用下面我将能够访问$scope,但是当我console.log($scope)$scope.user.zoomlvl它不存在.

我无法弄清楚如何访问MenuSideController$ scope并使用valZoom变量更新它.

var appElement = document.querySelector('[ng-app=theApp]');
var $scope = angular.element(appElement).scope();
console.log($scope);
$scope.$apply(function() {
    $scope.user.zoomlvl = valZoom;
});
Run Code Online (Sandbox Code Playgroud)

tas*_*ATT 72

在没有看到标记的情况下,我想MenuSideController的范围是您选择的范围的子范围.

虽然可以像这样遍历树(假设我们想要的范围是第一个孩子):

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

只选择附加特定控制器的元素更简单.

假设您正在使用该ng-controller指令:

<body ng-controller="MenuSideController"></body>
Run Code Online (Sandbox Code Playgroud)

改为:

var controllerElement = document.querySelector('body');
var controllerScope = angular.element(controllerElement).scope();
console.log(controllerScope.user);
Run Code Online (Sandbox Code Playgroud)

演示: 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';
  });
});
Run Code Online (Sandbox Code Playgroud)

  • 我只是偶然发现了Google的这个答案,并且使用该元素访问范围有一个非常重要的警告 - [它仅在Angular的调试数据打开时才有效!](https://docs.angularjs.org/guide/production #disabling-debug-data)鉴于你可以通过在生产中关闭调试数据来获得相当大的性能提升,我对依赖这种方法有些警惕. (7认同)