roscioli
roscioli

Reputation: 1230

Share data between two controllers in angularjs using restangular

I am fairly new to angularjs, so please bear with me.

I have two controllers, one of which has a Restangular call to load a certain json object. How do I access this same json object in another controller without making another Restangular call?

I already tried making a factory that shares the object, but this is far from working.

app.factory('Data', function() {
    return []
}

app.controller("FirstCtrl", function ($scope, AudioRestangular, Data) {
    $scope.audios_full = Data
    // load data into $scope.audios_full using restangular
}

app.controller("SecondCtrl", function ($scope, AudioRestangular, Data) {
    /*
     * $scope.second_ctrl_audios = ?
     * get data from FirstCtrl's audios_full
     * and store it in this $scope.second_ctrl_audios
    */
}

Upvotes: 0

Views: 695

Answers (1)

Michal Charemza
Michal Charemza

Reputation: 27012

You can go down the custom service / factory route, to effectively create your own caching layer as you suggest, or you can enable caching in Restangular. From https://github.com/mgonto/restangular#can-i-cache-requests

RestangularProvider.setDefaultHttpFields({cache: true});

You can probably put this in the "run" call of the app, like so:

app.run(function(RestangularProvider) {
  RestangularProvider.setDefaultHttpFields({cache: true});
});

Upvotes: 1

Related Questions