programing

외부에서 AngularJS 액세스 컨트롤러 $scope

runtoyou 2023. 2. 13. 23:08
반응형

외부에서 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내면에서나 볼 수 있는 가치들이죠

하지만 어디선가 봤는데, 아래를 사용해서$scope근데 제가console.log($scope)$scope.user.zoomlvl그것은 존재하지 않는다.

액세스 방법을 찾을 수 없습니다.MenuSideController$125 및 업데이트:valZoom변수.

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

마크업이 표시되지 않으면 MenuSideController의 스코프는 선택한 스코프의 자스코프라고 생각됩니다.

다음과 같이 트리를 아래로 이동할 수 있지만(필요한 스코프가 첫 번째 자식이라고 가정함)

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

특정 컨트롤러가 연결되어 있는 요소를 선택하는 것이 더 간단합니다.

를 사용하고 있다고 가정합니다.ng-controller지시:

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

언급URL : https://stackoverflow.com/questions/22570357/angularjs-access-controller-scope-from-outside

반응형