我想对一组对象进行分组
var data = [
{term: 'baz', description: 'Patient'},
{term: 'bar', description: 'Patient'},
{term: 'foo', description: 'Doctor'}
]
我现在想按下拉菜单的描述对这些数据进行分组。使用下划线 _.groupBy
我最终得到
$scope.grouped = _.groupBy(data, 'description')
{Patient: [
{term: 'baz', description: 'Patient'},
{term: 'bar', description: 'Patient'}
]
},
{Doctor: [
{term: 'foo', description: 'Doctor'}
]
}
你可以将 ng-switch 与对象键一起使用吗?
<div ng-switch="grouped">
<span ng-switch-when="Patient">
<p>Patients</p> // only shown once to categorize the data
// ng-repeat in here
</span>
<span ng-switch-when="Doctor">
<p>Doctors</p> // only shown once to categorize the data
// ng-repeat in here
</span>
</div>
我可以在分组之前在数组上使用ng-switch
,但分组的标题每次都会重复。实现与上面的 HTML 类似的效果(其中每个标题仅生成一次并对数据进行分组)的最佳方法是什么?
期望的输出是
<h1>Patients<h1>
<p>baz</p>
<p>bar</p>
<h1>Doctors</h1>
<p>foo</p>
最佳答案
您似乎想在 ng-repeat
内部使用它,在这种情况下,您可以使用对象键。
<div ng-repeat="(group, data) in grouped">
<div ng-switch="group">
<div ng-switch-when="Patient">
<h1>Patients</h1>
<p ng-repeat="patient in data">{{patient.term}}</p>
</div>
<!-- same for doctor -->
</div>
</div>
关于javascript - 使用对象键进行 ng-switch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30893856/