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);
}
2

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.