Share data between controllers in AngularJS

此生再无相见时 提交于 2019-12-10 22:08:25

问题


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!


回答1:


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.



来源:https://stackoverflow.com/questions/26445725/share-data-between-controllers-in-angularjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!