如何使用角度内置指令来显示产品组?

时间:2015-05-06 17:50:30

标签: angularjs

我正在使用AngularJS开发SPA,我的网页需要显示产品组列表及其相应的产品,如下所示

<h1>Product Group 1</h1>
<div class="row">
    <div>Product1 of group 1</div>
      ...
    <div>Product6 of group 1</div>
</div>
<div class="row">
    <div>Product 7 of group 1</div>
</div>

<h1>Product Group 2</h1>
<div class="row">
    <div>Product 1 of group 2</div>
</div>

每个<div class="row">代码最多包含6个产品元素

模型是像这样的产品组数组

[
 {
    title: 'Product Group 1',
    products: [
       'Product 1 of group 1',
          ...
       'Product 7 of group 1' 
    ]
 },
 {
     title: 'Product Group 2',
     products:[
        'Product 1 of group 2'
     ]
 }
]

每组中的产品数量可以变化,而不是固定,可能来自数据库数据,例如

这是否可以仅使用Angular内置指令来显示指定的模型数据,以便按照描述形成页面? 我尝试过ng-repeat,但似乎不是解决方案。我期待着AngularJS专家的任何想法。谢谢你的帮助!

1 个答案:

答案 0 :(得分:0)

假设您的数组名为$scope.groups,您只需执行此操作:

<h1 ng-repeat-start="group in groups">{{group.title}}</h1>
<div ng-repeat-end class="row">
  <div ng-repeat="product in group.products">{{product}}</div>
</div>

更新:要显示分成多行的产品,您可以添加一些预处理。通过将rows数组切割为6个元素的块来查看下面我计算products的片段:

&#13;
&#13;
angular.module('test', []).controller('test', function($scope) {

  $scope.groups = [
   {
      title: 'Product Group 1',
      products: [
         'Product 1 of group 1',
         'Product 2 of group 1',
         'Product 3 of group 1',
         'Product 4 of group 1',
         'Product 5 of group 1',
         'Product 6 of group 1',
         'Product 7 of group 1',
         'Product 8 of group 1'
      ]
   },
   {
       title: 'Product Group 2',
       products:[
          'Product 1 of group 2'
       ]
   }
  ];
  
  $scope.getRows = function(products) {
    var rows = [];
    var i = 0;
    while (products[i]) {
      var n = Math.floor(i/6);
      if (!rows[n]) { rows[n] = []; }
      rows[n].push(products[i]);
      i++;
    }
    return rows;
  };

});
&#13;
.row { margin: 1em; border: 1px solid #ddd; }
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="test" ng-controller="test">
  
  <h1 ng-repeat-start="group in groups"
      ng-init="rows = getRows(group.products)">{{group.title}}</h1>
  <div class="row"
       ng-repeat-end
       ng-repeat="row in rows">
    <div ng-repeat="product in row">{{product}}</div>
  </div>
  
</div>
&#13;
&#13;
&#13;

您还有其他方法可以做&#34;分页&#34;你的结果如果你是usig Angular 1.4就更容易了,更多例子见这个答案:

Filter results 6 through 10 of 100 with ng-repeat in AngularJS