我正在尝试学习如何使用Angular加载JSON。我是这两个主题的初学者,我坚持一些非常初学的话题。
我有一个名为food.json的JSON文件。它有这样的结构:
[
{"uid":"55","title":"Nussbrot","code":"U VP 0000030","unit":[{"title":""}],"unitgram":"0","unitgram_second":"0","sorting":"0"},
{"uid":"58","title":"Walnu\u00dfbrot","code":"X 39 2000002","unit":[{"title":"Scheiben"}],"unitgram":"45","unitgram_second":"0","sorting":"0"}
]
按照http://toddmotto.com/ultimate-guide-to-learning-angular-js-in-one-day/的说明,我有一个这样的控制器:
myApp.controller('EmailsCtrl', ['$scope', function ($scope) {
$scope.foodlist = {};
$scope.foodlist.foodtitle = '';
$http({
method: 'GET',
url: 'food.json'
})
.success(function (data, status, headers, config) {
$scope.foodlist = data.; //I don't know what to call here as my data elements have no names?
})
.error(function (data, status, headers, config) {
//error
});
}]);
我遇到的第一点是,如果JSON对象没有名称,如何将数据分配给我的'$ scope.foodlist'?
I've built a Plunkr of my not-working attempts so far,非常感谢a)读取JSON和b)将JSON数据分配给控制器中的值。
答案 0 :(得分:0)
ng-repeat
将迭代数据中的对象数组
你只需要使用:
<li ng-repeat="food in foodlist">
然后在循环的每次传递中,angular将引用数组中的当前对象以生成类似{{ food.title }}
的输出
我更新了您的demo here
修改强烈建议您一步一步地浏览angular docs网站上的教程
答案 1 :(得分:0)
第一个问题出在控制器定义中:您正在尝试引用$ http,但您没有将其传入。
myApp.controller('EmailsCtrl', ['$scope', '$http', function ($scope, $http) {
然后在success
上data
参数就是您的foodlist
:
.success(function (data, status, headers, config) { $scope.foodlist = data; })
最后,在你的html中,ng-repeat
应该是这样的:
ng-repeat="food in foodlist"