Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sharing ajax data between multiple controllers in angular using service

Tags:

angularjs

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.

like image 374
m0rjjj Avatar asked Nov 10 '22 16:11

m0rjjj


1 Answers

It happens because the factory should be defined by different way.

(I took dummy URL only to load data by async way)

HTML

<div ng-controller="NotificationBoxController">
    <button ng-click="showMe();">press  me</button>
    <pre>NotificationBoxController: {{items.getList()|json}}</pre>
</div>

<div ng-controller="NotificationController">
    <pre>NotificationController: {{items.getList()|json}}</pre>
</div>

JS

var pqsAppModule = angular.module('myApp', []);
pqsAppModule.controller('NotificationBoxController',function($scope,items) {
    $scope.items = items;

    $scope.showMe= function(){
     items.query();   
    }
});

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


pqsAppModule.factory('items', function ($http) {

    var current = {};    

    var address = 'Singapore, SG, Singapore, 153 Bukit Batok Street 1';
    var URL = 'http://maps.googleapis.com/maps/api/geocode/json?address=' + address + '&sensor=true';

       var factory = {            
           query: function () {                
                var data = $http({method: 'GET', url:URL}).then(function (result) {
                           current = result.data.results[0];                            
                        }, function (result) {
                            alert("Error: No data returned");
                        });  
            },
            getList: function () {                
               return current;
            }
       }       
        return factory; 
  });

Demo Fiddle

From this example we call items.getList() from HTML for both controllers. But if we want to update the model through the controller, we need a listener like $watch

like image 72
Maxim Shoustin Avatar answered Nov 15 '22 12:11

Maxim Shoustin