3

I use the following factory to fetch data from API and store it to local variable called apiData.

app.factory('MyFactory', function($resource, $q) {

    var apiData = [];
    var service = {};

    var resource = $resource('http://example.com/api/sampledata/');

    service.getApiData=function() {
        var itemsDefer=$q.defer();
        if(apiData.length >0) {
            itemsDefer.resolve(apiData);
        }
        else
        {
            resource.query({},function(data) {
                apiData=data;
                itemsDefer.resolve(data)
            });
        }
        return itemsDefer.promise;
    };

    service.add=function(newItem){
        if(apiData.length > 0){
            apiData.push(newItem);
        }
    };

    service.remove=function(itemToRemove){
        if(apiData.length > 0){
            apiData.splice(apiData.indexOf(itemToRemove), 1);
        }
    };

    return service;

});

I inject the apiData into my controllers the following way:

 $routeProvider
    .when('/myview', {
        templateUrl: 'views/myview.html',
        controller: 'MyController',
        resolve: {
            queryset: function(MyFactory){
                return MyFactory.getApiData();
            }
        }
    })

app.controller('MyController', ['$scope', 'queryset',
    function ($scope, queryset) {
        $scope.queryset = queryset;
    }
]);

Is it a good way to share a promise between different controllers or I better to use local storage or even cacheFactory?

How can I rewrite MyFactory add() and remove() methods so that I can keep my shared variable in a current state (no API update/create/delete calls needed)?

Thank you!

nickbusted
  • 1,029
  • 4
  • 18
  • 30
  • possible duplicate of [Sharing data between AngularJS controllers but having the shared data come from an Ajax call](http://stackoverflow.com/questions/15097961/sharing-data-between-angularjs-controllers-but-having-the-shared-data-come-from) – rxgx Oct 19 '14 at 01:18

1 Answers1

0

You should use $resource to get $promise eg: resource.query().$promise instead of $q.defer() for cleaner code. Otherwise you are good to go. You could use $cacheFactory, but you can also use local var.

Isn't your shared variable in a current state with current code?

I recommend you take a look at ui-router and its nested and abstract views, where resolved values are available to child controllers.

terafor
  • 1,620
  • 21
  • 28