来自外部的 AngularJS 访问控制器 $scope [英] AngularJS access controller $scope from outside

查看:36
本文介绍了来自外部的 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';
}]);

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

I have the above controller and it sets a $scope which I can only ever access the values from inside.

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

But I seen somewhere that using the below I would be able to access the $scope but when I console.log($scope) the $scope.user.zoomlvl it doesn't exist.

我不知道如何访问 MenuSideController $scope 并使用 valZoom 变量更新它.

I cannot figure out how to access the MenuSideController $scope and update that with the valZoom variable.

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

推荐答案

如果没有看到标记,我猜 MenuSideController 的作用域是您选择的作用域的子作用域.

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.

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

Assuming you are using the ng-controller directive:

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

改为:

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

演示: 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';
  });
});

这篇关于来自外部的 AngularJS 访问控制器 $scope的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆