2017-01-10 6 views
1

컨트롤러가 두 개 있습니다. 1. 기본 컨트롤러와 2. 결함 컨트롤러는 모두 서로 다른 파일입니다. 하나의 컨트롤러에서 다른 컨트롤러로 스코프 값이나 변수를 전달하고 싶습니다. 같은 파일에있는 두 컨트롤러가 모두 공유 할 수는 있지만 문제는 파일이 다르다는 것을 의미합니다.하나의 컨트롤러 파일에서 다른 파일로 범위를 전달할 수 있습니까?

하나의 컨트롤러에서 다른 컨트롤러로 스코프를 전달하려면 어떻게해야합니까?

+0

서비스를 이용하는 것은 갈 길이지만'$ rootScope'을 사용해서도 할 수 있습니다. (권유는 안된다. es) –

답변

0

서비스를 사용하는 것이 컨트롤러간에 통신하는 가장 좋은 방법입니다. https://docs.angularjs.org/guide/services

+0

예, 두 파일 모두에 대해 나머지 서비스를 사용하고 있지만 공통 값을 다른 컨트롤러와 공유하는 방법은 무엇입니까? – user3114967

0

다음은 각 초기화 한 후 바로 HTML에서이 두 파일을 포함해야합니다 귀하의 컨트롤러

//controller in file one 
var app = angular.module('myApp'); // don't use [] if module is already inititalized 
app.controller('settingCtrl', function($scope, sharedService){ 
var shared = "Biscuits"; 
sharedService.setShared(shared); 
}) 

//controller in file two 
var app = angular.module('myApp'); 
app.controller('readingCtrl', function($scope, sharedService){ 
var shared= sharedService.getShared(); 
console.log(shared); // 'Biscuits', recieved from other controller 
}) 

에이 서비스를 주입하는 서비스 지금

var app = angular.module('myApp',[]); 
app.service('sharedService', function(){ 
this.shared = null; 
return { 
    setShared: function(val){this.shared = val;}, 
    getShared: function(){return this.shared;} 
} 
}) 

쓰기 하는 방법

+0

두 개의 다른 파일에서 두 컨트롤러를 사용할 수 있습니까? – user3114967