반응형
angular.js의 컨트롤러 간에 변수 공유
앵글을 처음 접하는 사람인데 앵글 컨트롤러 간에 변수를 어떻게 공유할 수 있는지 궁금합니다.다음 스크립트를 사용하고 있습니다.
Main.js의 경우:
function MainCntl($scope) {
---code
}
function SearchCtrl($scope, $http) {
$scope.url = 'http://10.0.0.13:9000/processAdHoc';
$scope.errorM = "No results";
$scope.search = function() {
$http.post($scope.url, { "data" : $scope.keywords}).
success(function(data, status) {
$scope.status = status;
$scope.data = data;
$scope.result = data;
alert('yes');
})
.
error(function(data, status) {
$scope.data = data || "Request failed";
$scope.status = status;
alert('no');
$scope.result = "failed";
});
};
}
Index.html의 경우
<body ng-controller="MainCntl" >
---code
<div ng-controller="SearchCtrl">
<form class="well form-search">
<div class="ui-widget">
<label for="tags"></label>
<a ng-click="search()"><input type="image" src="../../images/search1.png" class="searchbox_submit" /></a>
<input ng-model="keywords" placeholder="Shadow Search" id="tags" class="input-medium search-query rounded" />
</div>
</form>
</div>
---code
<p ng-model="result">
{{result}}
</p>
</body>
데이터를 전송하고 답변을 받는 Ajax에서는 모든 것이 정상적으로 동작하고 있습니다.제 질문은 다음과 같습니다.
SearchCtrl 함수에는 나중에 Index.html에서 참조되는 $scope.result라는 변수가 있습니다.변수를 포함하는 HTML 코드를 SearchCtrl 컨트롤러에 삽입하면 정상적으로 동작하지만 MainCtrl 컨트롤러에 삽입되어 있으면 동작하지 않습니다.이 변수를 컨트롤러 간에 공유하려면 어떻게 해야 합니까?
잘 부탁드립니다
서비스를 사용하여 두 컨트롤러에 모두 주입하고 스코프 변수를 서비스 변수에 참조합니다.
예:
angular.module("yourAppName", []).factory("myService", function(){
return {sharedObject: {data: null } }
});
function MainCtrl($scope, myService) {
$scope.myVar = myService.sharedObject;
}
function SearchCtrl($scope, $http, myService) {
$scope.myVar = myService.sharedObject;
}
템플릿에서 다음 작업을 수행합니다.
{{myVar.data}}
See an example Angular v1.1.5 사용
이 오브젝트를 내부 오브젝트에 넣는 이유는 참조를 유지하기 위해서입니다.이 오브젝트를 "shared Object" 없이 유지하고 해당 오브젝트를 변경하면 바인딩은 오래된 참조를 가리키고 템플릿에는 아무것도 표시되지 않습니다.
언급URL : https://stackoverflow.com/questions/16508666/sharing-a-variable-between-controllers-in-angular-js
반응형
'programing' 카테고리의 다른 글
LWP로 JSON POST 요청을 하려면 어떻게 해야 하나요? (0) | 2023.03.08 |
---|---|
유형에 대한 속성을 찾을 수 없습니다...커스텀 스프링 데이터 저장소 (0) | 2023.03.08 |
Javascript에서 CSV 파일을 어레이에 로드합니다. (0) | 2023.03.08 |
html 내의 각도 함수를 호출합니다. (0) | 2023.03.08 |
비동기 redux 액션 성공 시 다른 루트로 이행 (0) | 2023.03.08 |