我正在Angular中创建一家商店,我有多个类别,每个类别中都有产品。我想将每个类别划分为一个单独的div,然后在单独的div中列出每个产品。

这是我希望输出看起来像的样子:



<div>
  <h2>category1</h2>
  <div>Product 1</div>
  <div>Product 2</div>
</div>

<div>
  <h2>category2</h2>
  <div>Product 3</div>
  <div>Product 4</div>
</div>





这是我到目前为止的内容:



(function() {
  var app = angular.module('store', [ ]);

  app.controller('StoreController', function() {
    this.items = products;
  });

  var products = [{
    category1: [{
      name: "Product 1",
      description: "Lorem ipsum dalor sit amet"
    }, {
      name: "Product 2",
      description: "Lorem ipsum dalor sit amet"
    }],
    category2: [{
      name: "Product 3",
      description: "Lorem ipsum dalor sit amet"
    }, {
      name: "Product 4",
      description: "Lorem ipsum dalor sit amet"
    }]
  }];
})();

<!DOCTYPE html>
<html ng-app="store">

  <head>
    <link rel="stylesheet" href="style.css">
  </head>

  <body ng-controller="StoreController as store">

    <div ng-repeat="category in store.items">
      <h2>{{category}}</h2> <!-- Category title here -->
      <div ng-repeat="item in category">{{item.name}}</div>
    </div>

    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.3/angular.min.js"></script>
    <script type="text/javascript" src="app.js"></script>
  </body>

</html>





Here's a Plunker

最佳答案

您的ng-repeat应该如下所示:

<div ng-repeat="category in store.items[0]">
    <h2>category{{$index+1}}</h2>
    <div ng-repeat="item in category">
      {{item.name}}
    </div>
</div>


这是工作示例:



(function() {
  var app = angular.module('store', []);

  app.controller('StoreController', function() {
    this.items = [{
    something: [{
      name: "Product 1",
      description: "Lorem ipsum dalor sit amet"
    }, {
      name: "Product 2",
      description: "Lorem ipsum dalor sit amet"
    }],
    category2: [{
      name: "Product 3",
      description: "Lorem ipsum dalor sit amet"
    }, {
      name: "Product 4",
      description: "Lorem ipsum dalor sit amet"
    }]
  }];;
  });


})();

<!DOCTYPE html>
<html ng-app="store">

<head>
  <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.3/angular.min.js"></script>
</head>

<body ng-controller="StoreController as store">

  <div ng-repeat="(key, category) in store.items[0]">
    <h2>{{key}}</h2>
    <!-- Category title here -->
    <div ng-repeat="item in category">
      {{item.name}}
    </div>
  </div>
</body>

</html>

09-05 20:17