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
  • 42,346
  • 14
  • 112
  • 132
clifford.duke
  • 3,850
  • 10
  • 35
  • 62

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
  • 42,346
  • 14
  • 112
  • 132