假设我有下一个json文件:
[{'car' : 'bmw', 'type' : '318'},
{'car':'bmw', type : '745'},
{'car' : 'porsche', 'type' : '911'}]
我希望使用角度使用
创建一个列表<ul><li ng-repeat="item in cars"><h4>Car:{{item.car}}</h4><h4>Type:{{item.type}}</li><ul>
我得到一个列表显示:
Car: BMW
Type : 318
Car: BMW
Type : 745
Car: Porsche
Type: 911
我可以使用一些角度表达式来第二次不显示宝马,例如某些当前汽车=以前的汽车没有显示。所以我会得到一个列表显示
Car: BMW
Type: 318
Type: 745
Car: Porsche
Type: 911
我变得非常困难,帮助将不胜感激!
答案 0 :(得分:3)
您可以使用groupBy
模块的angular-filter
在html中包含angular-filter.js,然后执行以下操作
更新您的模块
angular.module("myApp", ['angular.filter'])
更新您的标记
<ul>
<li ng-repeat="(key,value) in cars | groupBy : 'car'">
Car:{{key}}
<h4 ng-repeat="item in value">
Type:{{item.type}}
</h4>
</li>
<ul>
答案 1 :(得分:2)
在javascript级别重新组织数据可能更容易。如果您有一个由car
键入的字典,其中包含所有type
的列表,则将它们分成单独的列表会更容易。基本上,我建议您按车分组数据并附加到该车的类型列表中。
因此,如果您可以使您的对象列表如下所示:
var data = {
bmw: {
name: "bmw",
types: ["318", "745"]
},
porche: {
name: "porche",
types: ["911"]
}
};
然后你的HTML变得更简单了:
<div ng-repeat="brand in data"> <!-- This is ng-repeat over the properties of an object -->
Car: {{brand.name}}
<ul>
<li ng-repeat="type in brand.types">{{type}}</li>
</ul>
</div>
如果您可以更改您的JSON以更好地适合整理您的表单,那将是最好的。否则,您可以使用一些javascript来转换数据:
$scope.data = {};
$scope.originalJson.forEach(function (obj) {
var key = obj.car;
if ($scope.data[key] === undefined) {
$scope.data[key] = {
name: key,
types: []
};
}
$scope.data[key].types.push(obj.type);
});
如果更改此数据的形式不会影响应用程序的其他部分,则此想法有效。显然,这可能不是最佳选择,但它确实适用于您的问题。
答案 2 :(得分:1)
您可以在此使用ng-if
,例如ng-if="item.car != cars[$index-1].car"
<div ng-app="myApp" ng-controller="myCtrl" id="add-container-access" ng->
<input type="text" ng-model="query">
<ul>
<li ng-repeat="item in cars|filter: query" ng-class="{'hide-list-style':!showCar}"
ng-init="showCar = (item.car != cars[$index-1].car)">
<h4 ng-if="showCar">Car:{{item.car}}</h4>
<h4>Type:{{item.type}}</h4>
</li>
<ul>
</div>