2016-08-23 2 views
1

컨트롤러에서 서비스로 정보를 전달하는 방법이 있습니까? 서비스에서 컨트롤러로 정보를 전달해야한다는 것을 알고 있지만 내 문제를 설명해 드리겠습니다.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이라는 함수를 호출합니다.

그래서, 내 질문은 :

은 내가 ControllerTwoServiceTwo의 객체 vm.video를 전달할 수 있습니다, 그래서 나는 미래에 그것을 사용할 수 있습니까?

감사합니다!

+2

서비스는 싱글 톤이므로 서비스를 다시로드 할 때까지 vm.video를 ServiceTwo에 저장할 수 있습니다. 또한 localStorage, sessionStorage 또는 $ http 캐시를 사용할 수도 있습니다 ... 필요에 따라 다릅니다. – krutkowski86

답변

0

서비스는 사용자가 애플리케이션 전반에서 자료 (데이터 및 메소드)를 공유하기 위해 만들어졌습니다. 그래서 간단하게 질문에 대답하십시오 : 절대적으로 네, 당신은 당신의 물건을 당신의 서비스에 전달할 수 있습니다. 그리고, 어떤 쉽게 ...

ServiceOne & ServiceTwo는 모든 컨트롤러에 액세스 할 수 수 없습니다, 당신은 서비스에 "뭔가를 전달"할 경우이만큼 간단합니다

ControllerOne.$inject = ['$scope', '$state', 'ServiceOne', 'ServiceTwo']; 
function ControllerOne($scope, $state, ServiceOne, ServiceTwo) { 

    function loadData(){  
    var videoId = String($stateParams.videoId); 
    ServiceOne.getVideo(videoId) 
    .then(function(video) { 
     vm.video = video; 
     ServiceTwo.video = video; //bam, you're done 
    }); 
    } 
} 

동영상은 앱을 다시 시작할 때까지 유지됩니다.

ControllerOne.$inject = ['$scope', '$state', 'ServiceOne', 'ServiceTwo']; 
function ControllerOne($scope, $state, ServiceOne, ServiceTwo) { 
    // now you can access it from your other controller 
    var videoStoredInServiceTwo = ServiceTwo.video; 
} 

알아 두어야 할 것은 타이밍입니다. 비디오를 검색하기 전에 ServiceTwo에 비디오가 있는지 확인할 수 있습니다.

if(ServiceTwo.video) { 
    videoStoredInServiceTwo = ServiceTwo.video; 
    } 
관련 문제