gpt4 book ai didi

javascript - AngularJS Controller 工厂剩余 JSON

转载 作者:行者123 更新时间:2023-11-28 05:42:27 25 4
gpt4 key购买 nike

我正在尝试从多个 Controller 调用工厂。该工厂获取 JSON 数据。当我尝试直接从 Controller 调用时,我可以成功。现在我刚刚添加了一个工厂,控制台中没有错误,但屏幕上也没有任何内容。这是代码:

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 检索数据,您应该从 getObjects 函数返回一个带有 .then 函数的 Promise 到链式 Promise。在 Controller 内部,您可以使用 .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"}];
});
}
}
});

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;
});
});

关于javascript - AngularJS Controller 工厂剩余 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38812397/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com