[英]AngularJS Controller Factory rest JSON
我试图从多个控制器调用工厂。 这个工厂获得JSON数据。 当我尝试直接从控制器调用时,我可以成功。 现在我刚刚添加了一个工厂,控制台没有错误,但也没有任何问题。 这是代码:
html模板:
<!-- 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"}];
});
}
}
});
为了从工厂函数getObjects
检索数据,你应该使用.then
函数从getObjects
函数返回一个promise以链接promise。 在控制器内部,您可以使用.then
函数回调调用getObjects
来接收响应。
厂
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"}];
});
}
}
});
调节器
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;
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.