hco hco - 4 months ago 13
Javascript Question

AngularJS Controller Factory rest JSON

I am trying to call a factory from multiple controllers. This factory get JSON data. I can succeed it when I tried calling from controller directly. Now I just added a factory and there is be no error in console but nothing come to screen also. Here is the code:

html template:

<!-- Schools -->
<div class="row">
<h3 class="text-center">Schools and Associations</h3>
<ul class="gallery gallery1" ng-controller="SchoolsCtrl">
<li ng-repeat="school in schools" class="card">
<a ng-href="{{school.url}}" target="_blank">
<img ng-src="{{school.thumbUrl}}" class="img-responsive">
<p class="text-center">{{school.name}}</p>
<p class="text-center">{{school.time}}</p>
</a>
</li>
</ul>
</div>


controller.js:

var mainApp = angular.module('mainApp', ['bootstrapLightbox', 'ngAnimate']);

mainApp.controller('CompaniesCtrl', function($scope, GalleryService) {
$scope.companies = GalleryService.getObjects('app/common/companies.json');
});

mainApp.controller('WorksCtrl', function($scope, GalleryService) {
$scope.works = GalleryService.getObjects('app/common/freelance-projects.json');
});

mainApp.controller('SchoolsCtrl', function ($scope, GalleryService) {
$scope.schools = GalleryService.getObjects("app/common/schools.json");
});


service.js:

mainApp.factory('GalleryService', function ($http) {
return {
getObjects: function (jsonUrl) {
$http.get(jsonUrl)
.success(function (data) {
return data;
})
.error(function (data, status, error, config) {
return [{heading:"Error", description: "Could not load json data"}];
});
}
}
});

Answer

In order to retrieve data from factory function getObjects you should return a promise from getObjects function with .then function to chain promise. Inside a controller you can make getObjects call with .then function callbacks to receive response.

Factory

mainApp.factory('GalleryService', function ($http) {
    return {
        getObjects: function (jsonUrl) {
            return $http.get(jsonUrl)
                .then(function (resp) {
                    return resp.data; 
                }, function (res) {
                    return [{heading:"Error", description: "Could not load json data"}];
                });
        }
    }
});

Controller

var mainApp = angular.module('mainApp', ['bootstrapLightbox', 'ngAnimate']);

mainApp.controller('CompaniesCtrl', function($scope, GalleryService) {
  GalleryService.getObjects('app/common/companies.json').then(function(data){
    $scope.companies = data;
  });
});