ANshul Sharma
ANshul Sharma

Reputation: 325

JSON data from factory not being fetched

This is my controller:

 mainApp.controller('recordController', [ '$scope', 'record', 'recordSlides', function($scope, record, recordSlides) {
    $scope.pageClass = 'page page-record';
    record.success(function(data){
        $scope.tracks = data;
    });

    $scope.myInterval = 3000;
    recordSlides.success(function(data){
        $scope.slides = data;
    });
        /*$scope.slides=[
            {
                "image": "http://lorempixel.com/400/200/"
            },
            {
                "image": "http://lorempixel.com/400/200/food"
            }
        ]*/}])

These are the factories I am injecting to the above controller:

mainApp.factory('record',['$http', function($http){ // for delivering records data
    return $http.get('./data/record.json')
        .success(function(data) {
            return data;
        })
        .error(function(err) {
            return err;
        });
}]);

mainApp.factory('recordSlides',['$http', function($http){ // for delivering slides on record page
    return $http.get('./data/recordSlides.json')
        .success(function(data) {
            return data;
        })
        .error(function(err) {
            return err;
        });
}]);

The JSON data from the factory "record" is being pulled and displayed properly but the data from the "recordSlides" factory is not being displayed. It works when I directly pass the json data to "slides" (code Commented out) but when I inject the controller and pass the JSON data through factory it is not working.

this is recordSlides.json:

[{
    "image": "http://lorempixel.com/400/200/"
  },
  {
    "image": "http://lorempixel.com/400/200/food"
}]

Your help is appreciated.

Thanks

Upvotes: 0

Views: 53

Answers (1)

Dmitry Lobov
Dmitry Lobov

Reputation: 303

in a service:

var deferred = new $q.defer();
$http({...})
.success(function (resp) {
    deferred.resolve(resp);
})
.error(function(err){
    deferred.reject(err); 
}
return deferred.promise;

and in controller:

record.then(function(data){
    $scope.tracks = data;
});
recordSlides.then(function(data){
    $scope.slides = data;
});

Dont forget to include $q dependency in a service

Upvotes: 2

Related Questions