Search code examples
jsonangularjsangularjs-scopeangularjs-ng-repeatangularjs-service

Using JSON response in more than one controller with angularjs


My website is a posting site with posts from different countries. On homepage load i will make a service call and get all the posts using a controller($http) and will be displayed on the homepage.

In the homePage two dropdown and a button are given from which user can choose or filter the posts by country and theme, and results will be in different page.

I want to use the same controller response data without making a new service call to filter the response and show the results.

Please help me on how can i use the same controller or do i need to use a factory and then make the factory as a dependent to my controller??


Solution

  • The best way to do that is to do with a Service. Service is a Singleton, which means that construction will happen only once. In Service constructor you will load posts, and the from any controller you can access your data.

    angular.module('myApp').service('myPostService', function($http) {
      var Service = {
        postList: []
      };
    
      // Here load over $http service your posts and then put it into Service.postList.
    
      return Service;
    });
    

    Then inject the service and use the posts

    angular.module('myApp').controller('HomeCtrl', function(myPostService) {
      $scope.postList = Service.postList;
    });
    

    And in HTML iterate over it, filter and do whatever you want.