2013-08-30 3 views
0

현재 저는 angularJS를 배우려고하고 있으며 컨트롤러간에 데이터에 액세스하는 데 문제가 있습니다.angularjs에서 컨트롤러간에 데이터를 공유하는 방법

내 첫 컨트롤러가 내 API에서 통화 목록을 가져 와서 $ scope.currencies에 지정합니다. 편집을 클릭하면 다른 컨트롤러를 사용하는보기가 전환됩니다. batarang를 사용하여 디버깅 할 때 지금, $ scope.currencies 통화 객체의 배열을 보여 않습니다

{ 
    currencies: [{ 
     CurrencyCode: HKD 
     Description: HONG KONG DOLLAR 
     ExchangeRateModifier: * ExchangeRate: 1 
     DecimalPlace: 2 
    }, { 
     CurrencyCode: USD 
     Description: US DOLLAR 
     ExchangeRateModifier: * ExchangeRate: 7.7 
     DecimalPlace: 2 
    }] 
} 

하지만를 angular.copy, 널 (null)에서 $scope.copiedcurrencies 결과를 사용하는 경우.

function CurrencyEditCtrl($scope, $injector, $routeParams) { 
    $injector.invoke(CurrencyCtrl, this, { $scope: $scope }); 
    $scope.copiedcurrencies = angular.copy($scope.currencies); 
    console.log($scope.copiedcurrencies); 
} 
+0

[가능한 한 컨트롤러에서 AngularJS를 호출 할 수 있습니까?] (http://stackoverflow.com/questions/9293423/can-one-controller-call-another-in-angularjs) – m59

+0

내 솔루션이 도움이되지 않습니까? – m59

+0

좋아요! 다행히 도왔다! – m59

답변

2

컨트롤러간에 데이터를 공유하는 가장 일반적이며 권장되는 방법은 서비스를 사용하는 것입니다. Click here for Live Demo (see app.js)

var app = angular.module('myApp', []); 

app.factory('myService', function() { 
    var myService = { 
    foo: 'bar' 
    }; 
    return myService; 
}); 

app.controller('myCtrl1', function(myService) { 
    console.log(myService.foo); 
    myService.foo = 'not bar anymore!'; 
}); 

app.controller('myCtrl2', function(myService) { 
    console.log(myService.foo); 
}); 

참고 : 서비스를 만드는 여러 가지 방법이 있습니다.

관련 문제