컨트롤러에서 서비스로 정보를 전달하는 방법이 있습니까? 서비스에서 컨트롤러로 정보를 전달해야한다는 것을 알고 있지만 내 문제를 설명해 드리겠습니다.AngularJS : 컨트롤러에서 서비스로 정보 전달
컨트롤러가 다르지만 동일한 모듈을 사용하는 두 개의 화면 (또는 두 개의 뷰)이 있습니다. ViewOne 및 ServiceOne이있는 ControllerOne과 ViewTwo 및 ServiceTwo가있는 ControllerTwo를 이름을 지어 봅시다.
ServiceOne
은 (원격 원점에서) 일부 json 데이터를 가져 오기 위해 http 요청을합니다. ControllerOne
에서 나는 모든 데이터를 얻기 위해 ServiceOne을 호출하는 기능을 가지고 있으며 ViewOne에서 원격 원점 (ControllerOne)에서 가져온 모든 비디오 목록을 보여줍니다. ViewTwo
(
(function() {
'use strict';
angular
.module('MyApp.MyModule')
.controller('ControllerOne', ControllerOne);
ControllerOne.$inject = ['$scope', '$state', 'ServiceOne'];
function ControllerOne($scope, $state, ServiceOne) {
var vm = angular.extend(this, {
videos: [],
navigateToVideo: navigateToVideo
});
ServiceOne.getAllVideos(function(data){
vm.videos = data;
});
function navigateToVideo(videoId) {
$state.go('app.video', { videoId: videoId });
}
}
})();
ViewOne
에서 매번 누군가가 동영상을 클릭, 내가 다른보기로 이동 한 다음 ControllerOne
은 다음과 같습니다
(function() {
'use strict';
angular
.module('MyApp.MyModule')
.factory('ServiceOne', ServiceOne);
ServiceOne.$inject = ['$http', '$q'];
function ServiceOne($http, $q) {
var url = 'https://THE_LINK_I_WANT_TO_GET_DATA_FROM';
var result = [];
var service = {
getAllVideos: getAllVideos,
getVideo: getVideo
};
return service;
function getAllVideos(callback){
$http.get(url)
.success(function(data) {
result = data.result;
callback(result);
});
}
function getVideo(videoId) {
for (var i = 0; i < result.length; i++) {
if (result[i].videoId === videoId) {
return $q.when(result[i]);
}
}
return $q.when(null);
}
}
})();
가 :
ServiceOne
에 대한 코드는 위에 표시된다 내 경우에는) 매개 변수가 전달됩니다 (고유 ID).
ControllerTwo
은 다음과 같습니다 다음 ControllerTwo
에서
(function() {
'use strict';
angular
.module('MyApp.MyModule')
.controller('ControllerTwo', ControllerTwo);
ControllerTwo.$inject = ['$scope', '$state', '$stateParams', 'ServiceOne'];
function ControllerTwo($scope, $state, $stateParams, ServiceOne) {
var vm = angular.extend(this, {
video: []
});
(function init(){
loadData();
})();
function loadData(){
var videoId = String($stateParams.videoId);
ServiceOne.getVideo(videoId)
.then(function(video) {
vm.video = video;
});
}
}
})();
내가 ControllerOne
에서 전달 된 매개 변수를 저장하고 videoId
에 저장합니다. 그럼 내가 찾고 있던 객체를 얻기 위해 ServiceOne
이라는 함수를 호출합니다.
그래서, 내 질문은 :
은 내가 ControllerTwo
ServiceTwo
의 객체 vm.video
를 전달할 수 있습니다, 그래서 나는 미래에 그것을 사용할 수 있습니까?
감사합니다!
서비스는 싱글 톤이므로 서비스를 다시로드 할 때까지 vm.video를 ServiceTwo에 저장할 수 있습니다. 또한 localStorage, sessionStorage 또는 $ http 캐시를 사용할 수도 있습니다 ... 필요에 따라 다릅니다. – krutkowski86