【问题标题】:How would I access this JSON data in AngularJS?我将如何在 AngularJS 中访问这些 JSON 数据?
【发布时间】:2013-10-31 04:51:53
【问题描述】:

我正在尝试学习如何使用 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 数据分配给控制器中的值方面提供任何指导。

【问题讨论】:

  • 您应该熟悉在 chrome 中单步执行 - 这允许您在 $scope.foodlist = ... 命令处放置一个断点,然后监视返回的变量 - 然后您将看到数据很可能是一个数组,这就是您需要分配的所有内容(我认为)。因此,您需要遍历数组以返回单个对象,就像您尝试做的那样。

标签: json angularjs


【解决方案1】:

ng-repeat 在您的情况下将迭代数据中的对象数组

你只需要使用:

<li ng-repeat="food in foodlist">

然后在循环的每一次传递中,angular 将引用数组中的当前对象以产生像{{ food.title }} 这样的输出

我更新了你的demo here

编辑强烈建议您逐步阅读 Angular 文档网站上的教程

【讨论】:

  • 感谢更新的 Plunkr,它清楚地显示了我哪里出错了。没错,AngularJS 文档比我尝试遵循的教程要好得多。
【解决方案2】:

第一个问题在控制器定义中:你试图引用 $http 但你没有传入它。

myApp.controller('EmailsCtrl', ['$scope', <b>'$http'</b>, function ($scope, <b>$http</b>) {

那么在success 上,你的data 参数就是你的foodlist

.success(function (data, status, headers, config) { $scope.foodlist = data; })

最后,在你的 html 中,ng-repeat 应该是这样的:

ng-repeat="food in foodlist"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-02
    • 2014-01-26
    • 2016-07-17
    • 1970-01-01
    • 2020-07-20
    • 2020-05-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多