Sharing ajax data between multiple controllers in angular using service

Viewed 3202

Hi I have two controllers

pqsAppModule.controller('NotificationBoxController',function($scope,items) {
    $scope.list = items.list();
})

and

pqsAppModule.controller('NotificationController',function($scope,items) {
    $scope.list = items.list();
})

I need to create an "items" service that would do an ajax request and return data for any controller which would have it injected. And I want, that the query will be done only once, and items will be shared between all controllers.

pqsAppModule.factory('items', function($http) {
    var items = [];
    var itemsService = {};
    $http.get('api/notification').then(function(response){
        items = response.data;
    });

    itemsService.list = function() {
        return items;
    };

    return itemsService;
});

But I don't understand why angular makes the request, and receives data, but all items in controllers are empty.

2 Answers
Related