javascript - 如何在 ng-repeat 中正确显示此 json 文件?

标签 javascript angularjs json

我正在尝试为我的网站创建商店页面。我想在 ng-repeat 中显示以下 json 文件:

{
  "cupcakes": {
      "Vanilla": [
          {"price":"9.99", "stock":"20", "amount":"8",
          "ingredients":"flour, sugar, vanilla extract",
          "popular":true}
      ],
      "Maple": [
          {"price":"9.99", "stock":"15", "amount":"8", 
          "ingredients":"flour, sugar, maple syrup",
          "popular":true}
      ]
  },
  "cookies": {
      "Vanilla": [
          {"price":"7.99", "stock":"50", "amount":"12", "ingredients":"flour, sugar, vanilla extract"}
      ],
      "Maple": [
          {"price":"7.99", "stock":"50", "amount":"12", "ingredients":"flour, sugar, maple syrup"}
      ]
  }
}

我想显示项目类型(纸杯蛋糕或 cookies ),然后是每个项目的类型( Vanilla 或枫糖),然后是唯一属性,并能够过滤和搜索它们。我在想我可能必须重组我的 json 文件,但我不确定。我是否应该使用 forEach 在我的 Controller 中提前整理项目?这是我的 Controller :

angular.module('root', [])
.controller("index", ['$scope', '$http', function ($scope, $http) {
    $scope.name = null;
    $scope.email = null;
    $scope.comments = null;
    $scope.reason = null;
    $scope.employees = [];
    $scope.items = [];


    $http.get('http://localhost:8000/employees.json').then(function(result) {
        $scope.employees = result.data.records;
    });

    $http.get('http://localhost:8000/inventory.json').then(function(result) {
        $scope.items = result.data;
    });

    $scope.isEnabled = function() {
        if ($scope.name && $scope.email && $scope.comments) {
            return false;
        }
        else {
            return true;
        }
    }
}])

最佳答案

在 Javascript 中,几乎一切都是数组。您可以遍历对象数组,或者在一个对象中遍历其属性。

下面的脚本应该可以完成这项工作。

<div ng-repeat="(itemLabel, itemValue)in items">
     {{itemLabel}}
     <div ng-repeat="(flavorLabel, flavorValue)in itemValue">
         {{flavorLabel}}
         <div ng-repeat="object in flavorValue">
             <div ng-repeat="property in object">
                 {{property}}
             </div>
         </div>
     </div>
</div>

jsfiddle

关于javascript - 如何在 ng-repeat 中正确显示此 json 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40809774/

相关文章:

javascript - 当使用 ionic 框架从 Angularjs 中的 ng-repeat 获取值时,如何重新填充动态 ng-model 字段

angularjs - 为 MEAN.JS 文章添加评论

jQuery .push() 不工作

javascript - 在 AngularJS 指令中使用 `require`

php - 使用带有 php 和 mysql 的 http 请求创建 android 应用程序

json - 'Response' 类型的参数不能分配给 'string' 类型的参数

javascript - 在javascript中声明可观察到的动态 knockout

javascript - jQuery: `:eq(i) ` 选择

javascript - 如何替换没有ID的元素的类名?

sql - AngularJS 不会获取由 socket.io 发出的新数据