如何列出AngularJS中的项目并按类别分隔,如下所示:
<h3>Products</h3>
<div ng-repeat="item in products">
<div>
{{item.category}}
</div>
<p>
{{item.name}}
</p>
<p>
{{item.price}}
</p>
</div>
$范围:
$scope.products = [
{
name:"product1",
price:"450",
category:"cat1"
},
{
name:"product2",
price:"450",
category:"cat2"
},
{
name:"product3",
price:"450",
category:"cat1"
}
];
我希望它看起来像这样:
CAT1
---&GT;产品1
---&GT;产品3
CAT2
---&GT;产品2 ...
请帮忙!
答案 0 :(得分:0)
见[小提琴])(http://jsfiddle.net/Lvc0u55v/2846/)
我做了一些格式化,以所需格式发送数据。
$scope.productCategories = {};
for (var i = 0; i < products.length; i++) {
if ($scope.productCategories[products[i].category] == undefined)
$scope.productCategories[products[i].category] = [];
$scope.productCategories[products[i].category].push({
name: products[i].name,
price: products[i].price
});
}
Html格式化已关闭,但我希望这能为您提供一个想法
答案 1 :(得分:0)
你可以在ng-repeat中使用groupBy过滤器。您应该在应用中添加groupBy过滤依赖项。
var app = angular.module("app",['angular.filter']);
app.controller("ctrl" , function($scope){
$scope.products = [ { name:"product1", price:"450", category:"cat1" }, { name:"product2", price:"450", category:"cat2" }, { name:"product3", price:"450", category:"cat1" } ];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-filter/0.4.7/angular-filter.js"></script>
<div ng-app="app" ng-controller="ctrl" class="panel-group" id="accordion">
<h3>Products</h3>
<div ng-repeat="(key,value) in products | groupBy: 'category'">
<div>
{{key}}
</div>
<div ng-repeat="item in value">
<p>
{{item.name}}
</p>
<p>
{{item.price}}
</p>
</div>
</div>
</div>