Search code examples
angularjsjsonp

Angular.JS share a single JSON object between controllers


I´m trying to code a CRUD app with Angular.JS, and I need your help to move on. This is the scenario:

  1. View 1 (index) gets JSONP data from a remote API and stores it.
  2. View 2 (master) shows data filtered on a grid
  3. View 3 (detail) shows an specific item selected on View 2

I did it already, but requesting the very same JSON object on each view, , but I think one only api call is enough.

I can´t figure out how to properly share this JSON object for all the controllers. I tried several tutorials on ngResource, $http, factories and services but still have not a clear path to go through.

How can I do this?

Any snippet or code sample you may share will be very useful to keep on tryin this thing...

Thanks in advance,

Ariel


Solution

  • Using services to cache and share the data across controllers would be the way to go. Since services in angular are singleton, the same copy of data can be shared. A service such as

    angular.module('myApp').factory('dataService', function($q, $resource) {
      var items=[];
      var service={};
      service.getItems=function() {
         var itemsDefer=$q.defer();
         if(items.length >0) 
            itemsDefer.resolve(data);
         else
         {
              $resource(url).query({},function(data) {
                 items=data;
                 itemsDefer.resolve(data)
              });        
         }
         return itemsDefer.promise;
      }
      return service;
    });
    

    Now in the controller you can inject the dataService and call the getItems method. This method returns a promise, which is either resolved using the cached data or by making remote request. And the controller code would look something like

    angular.module('myApp').controller('MyCtrl', function($scope,dataService) {
        dataService.getItems().then(function(items) {
            $scope.items=items;
        }
    });