【问题标题】:Parse JSON file with arrays using AngularJS使用 AngularJS 解析带有数组的 JSON 文件
【发布时间】:2014-05-15 14:12:23
【问题描述】:

我不确定如何在 AngularJS 的帮助下遍历这个 JSON 数据

{       
   {
      "1590": {
      "id": "1590",
      "id_site": "0",
      "id_merk": "7",
      "id_type": "209",
      "uitvoering": "Blue Lease Execut. HYbrid4 2.0 HDi 4D 147kW"
   },
   {
      "1590": {
      "id": "1590",
      "id_site": "0",
      "id_merk": "7",
      "id_type": "209",
      "uitvoering": "Blue Lease Execut. HYbrid4 2.0 HDi 4D 147kW"
   }
}

这就是我现在的 Angular 应用程序中的内容:

服务

(function () {

    var releasingService = function ($http) {

        var brands = [];
        $http.get('/releasing.json')
            .then(function(results) {
                brands = results;

        });

        this.getBrands = function () {
        return brands;
      };

   };

   releasingService.$inject = ['$http'];

   angular.module('releasingApp').service('releasingService', releasingService);

}());

查看

<select data-ng-model="brands" data-ng-options="brand.Id for brand in brands">
   <option value="">-- Selecteer een merk --</option>
</select>

当前视图未显示任何结果。我不知道如何处理数组中的不同对象。

任何帮助将不胜感激。

【问题讨论】:

  • 用 { { } } 看起来不像是一个有效的 json,你写的 json 是什么样子的吗?
  • 是的,这实际上是我从服务器请求 JSON 时的样子。所以我不能自己改变输出。

标签: json angularjs angularjs-ng-repeat arrays


【解决方案1】:

你不能迭代你的 JSON,因为它不是数组而是对象。

像这样设置大括号:

[
  {
    "1590": {
      "id": "1590",
      "id_site": "0",
      "id_merk": "7",
      "id_type": "209",
      "uitvoering": "Blue Lease Execut. HYbrid4 2.0 HDi 4D 147kW"
    }
  },
  {
    "1590": {
      "id": "1590",
      "id_site": "0",
      "id_merk": "7",
      "id_type": "209",
      "uitvoering": "Blue Lease Execut. HYbrid4 2.0 HDi 4D 147kW"
    }
  }
]

第二个选项是key-value 演示文稿:

{
  "1590": {
    "id": "1590",
    "id_site": "0",
    "id_merk": "7",
    "id_type": "209",
    "uitvoering": "Blue Lease Execut. HYbrid4 2.0 HDi 4D 147kW"
  },
  "1591": {
    "id": "1591",
    "id_site": "0",
    "id_merk": "7",
    "id_type": "201",
    "uitvoering": "Blue Lease Execut. HYbrid4 2.0 HDi 4D 142kW"
  }
}

所以 HTML 应该是这样的:

<select data-ng-model="selectedItem" 
        data-ng-options="key as value.uitvoering  for (key , value) in brands">
   <option value="">-- Selecteer een merk --</option>
</select>

Demo in Fiddle

助手 你可以使用这个在线助手:jsoneditoronline

【讨论】:

    【解决方案2】:

    我给你写一个例子:plnkr

    首先,您提供的 json 不是有效的 json。根据结构,您可能需要更改ng-options 中的表达式。然后,我建议您将 $http 承诺返回给控制器并在执行 ajax 后解析结果。最后,将结果呈现给 select 元素。我希望这能帮到您。如果您想了解更多选择选项的详细信息,还可以查看 api 文档ng on select

    【讨论】:

      猜你喜欢
      • 2023-01-07
      • 1970-01-01
      • 2015-09-15
      • 1970-01-01
      • 2014-03-29
      • 2020-02-04
      • 2020-07-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多