0

can you please tell how to how to read json file.I am able to read json file using controller .but there is way to read file from factory .When I use factory am getting null contend..why ? http://plnkr.co/edit/THdlp00GuSk1NS6rqe5k?p=preview

app.controller("ctrl",['$scope',"$http",'mainInfo',function(s,$http,mainInfo){
    s.students = [];
    s.guitarVariable = [];
    console.log(mainInfo);
   s.guitarVariable = mainInfo.content;

   /* $http.get('color.json').success (function(data){
        s.guitarVariable = data;
    }).error(function(err){
            alert(err);
        }); */



}])

Using this code in controller I am able to get data .But using factory I am getting null

   /* $http.get('color.json').success (function(data){
        s.guitarVariable = data;
    }).error(function(err){
            alert(err);
        }); */

2 Answers 2

0

Angular services are singletons. The purpose is to provide a single object that represents the service to rest of the application. You need to put the HTTP call as a method of the object that will returned from the service. You will then inject the service into your controller and call the service method from it. Here is an example:

SERVICE:

    app.factory('mainInfo', function($http) {

 return {
     //call this method from the controller
    getColors: function() {
       return $http.get('color.json'); //return the promise object. Use in controller
    }
  }
});

CONTROLLER:

app.controller("ctrl",['$scope',"$http",'mainInfo',function($http,mainInfo){
  mainInfo.getColors().success(function(data) {
    alert(data);
  }).error(function() {
    alert("Not working");
  });
}]);
Sign up to request clarification or add additional context in comments.

4 Comments

stil I am getting null..:(
Are you sure the request is working? Try to add an error() handler to the $http.get() promise and log a message to the console.
I am getting success in factory .but on controller I am getting null
Your $scope in your controller is missing ($scope, $http )
0

For a simple $http get of 1 file I would probably just do it in the controller, but if you want to use a factory you want to return the $http.get('file.json') and then use success to wait for the promise to resolve.

Looks like this plnkr

For an API I would use a $resource - video about resource setup

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.