0

I'm currently trying to learn angularJS and am having trouble accessing data between controllers.

My first controller pulls a list of currencies from my api and assigns it to $scope.currencies. When I click edit, what is supposed to happen is that it switches the view which uses another controller. now when debugging using batarang, $scope.currencies does show an array of currency objects:

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

But when using angular.copy, the $scope.copiedcurrencies result in null.

function CurrencyEditCtrl($scope, $injector, $routeParams) {
    $injector.invoke(CurrencyCtrl, this, { $scope: $scope });
    $scope.copiedcurrencies = angular.copy($scope.currencies);
    console.log($scope.copiedcurrencies);
}
m59
  • 43,214
  • 14
  • 119
  • 136
clifford.duke
  • 3,980
  • 10
  • 38
  • 63
  • possible duplicate of [Can one controller call another in AngularJS?](http://stackoverflow.com/questions/9293423/can-one-controller-call-another-in-angularjs) – m59 Aug 30 '13 at 06:44
  • Is my solution not helpful? – m59 Sep 02 '13 at 17:45

1 Answers1

2

The most common and recommended method for sharing data between controllers is to use a service. 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);
});

Note: there are several ways of creating a service.

m59
  • 43,214
  • 14
  • 119
  • 136