我正在尝试从我的代码中删除一个硬编码数组并放入一个我可以随时替换的平面文件中,因此我使用 HTTP get 来执行此操作。
使用下面的代码,它不会以我可以在我的标记中迭代它的方式返回结构。此外,出于某种原因,当我查看 Firebug 并查看请求时,它似乎调用了 4 次(!)。
var app = angular.module('MainEventApp', ['cloudinary']);
app.service('MainEventRepository', ['$http', function ($http) {
this.$http = $http;
this.getMainEvents = function () {
return this.$http.get('/main_events.json').then(function(response) {
return response;
});
}
}]);
app.controller("MainEventCtrl", ['$scope', 'MainEventRepository', function ($scope, MainEventRepository) {
$scope.main_events = MainEventRepository.getMainEvents();
}]);
main_events.json
[
{
"id": 1,
"roman_numeral": "I",
"name": "Hulk Hogan & Mr T vs Rowdy Roddy Piper & Paul Orndorff",
"venue": "Madison Square Garden",
"state": "New York",
"attendance": 19121
},
... and so on ...
]
我的标记:
ng-repeat='main_events in main_events'
最佳答案
在你的 Controller 中,完成 promise :
MainEventRepository.getMainEvents().then(function(data) {
$scope.main_events = data;
});
此外,在您的服务中,从响应中返回 data
对象:
return response.data;
关于javascript - 无法使用 AngularJS 中的 HTTP get 调用从 JSON 平面文件返回结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26428983/