각도는 각 컨트롤러에 대해 하나의 $ scope 개체를 만듭니다. 우리는 또한 모든 컨트롤러로부터 $ rootScope를받을 수 있습니다. 그러나 다른 컨트롤러에서 한 컨트롤러의 $ 범위에 액세스 할 수 있습니까? 종류 대답은 아니오입니다. 또한 우리 응용 프로그램이 다른 컨트롤러의 $ 범위에 액세스해야하는 경우, 우리는 아마도 잘못된 것을하고 있으며 우리는 문제를 다시 생각할 필요가 있습니다. 하지만 어쨌든 다른 컨트롤러의 $ scope에 액세스 할 수 있다면 서비스 내에 저장하십시오.
예제를 만들려고했는데, 이해하는 데 도움이되기를 바랍니다. $ HTTP 서비스
<!doctype html>
<html ng-app="app">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.18/angular.js"></script>
<script src="app.js"></script>
</head>
<body>
<div ng-controller="OneController">
<h2>OneController</h2>
<button ng-click="buttonClick()">
buttonClick on current scope
</button>
<button ng-click="buttonClickOnTwoController()">
buttonClick on TwoController's scope
</button>
</div>
<div ng-controller="TwoController">
<h2>TwoController</h2>
<button ng-click="buttonClick()">
buttonClick on current scope
</button>
<button ng-click="buttonClickOnOneController()">
buttonClick on OneController's scope
</button>
</div>
</body>
</html>
를 사용하여 귀하의 요구 사항에 따라 코드를 변경하고 app.js하십시오
var app = angular.module('app', []);
app.run(function ($rootScope) {
$rootScope.$on('scope.stored', function (event, data) {
console.log("scope.stored", data);
});
});
app.controller('OneController', function ($scope, Scopes) {
Scopes.store('OneController', $scope);
$scope.variable1 = "One";
$scope.buttonClick = function() {
console.log("OneController");
console.log("OneController::variable1", Scopes.get('OneController').variable1);
console.log("TwoController::variable1", Scopes.get('TwoController').variable1);
console.log("$scope::variable1", $scope.variable1);
};
$scope.buttonClickOnTwoController = function() {
Scopes.get('TwoController').buttonClick();
};
});
app.controller('TwoController', function ($scope, Scopes) {
Scopes.store('TwoController', $scope);
$scope.variable1 = "Two";
$scope.buttonClick = function() {
console.log("TwoController");
console.log("OneController::variable1", Scopes.get('OneController').variable1);
console.log("TwoController::variable1", Scopes.get('TwoController').variable1);
console.log("$scope::variable1", $scope.variable1);
};
$scope.buttonClickOnOneController = function() {
Scopes.get('OneController').buttonClick();
};
});
app.factory('Scopes', function ($rootScope) {
var mem = {};
return {
store: function (key, value) {
$rootScope.$emit('scope.stored', key);
mem[key] = value;
},
get: function (key) {
return mem[key];
}
};
});
당신은 또한 here
당신이 콘솔
에 넣어 밖으로 볼 수있는 실행 볼 수 있습니다
그래서 전역 변수와 같은 것을 원합니까? [$ rootScope] (https://docs.angularjs.org/api/ng/service/$rootScope)를 사용하는 것이 하나의 가능성입니다. – KRONWALLED