javascript - 使用对象键进行 ng-switch

标签 javascript angularjs

我想对一组对象进行分组

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/

相关文章:

javascript - 在 Vuejs 中解构或预过滤计算属性中的数据

angularjs - 递归 ui 路由器嵌套 View

javascript - 配置 Protractor 以忽略浏览器控制台错误

javascript - 不同 div 上同时发生的事件?

javascript - 扩展 javascript 函数作用域

javascript - 如何在html表格中添加动态行?

javascript - mongodb nodejs - 转换循环结构

javascript - 在 Angular 1.5 中使用 'one-directional binding' (<) 有什么意义?

angularjs - Angular 多槽嵌入作为属性,而不是元素

javascript - 无法使用 Angular 中的 $location 服务更改 URL 路径