【问题标题】:ng-repeat show subtitle for first type of itemng-repeat 显示第一类项目的字幕
【发布时间】:2016-08-08 20:33:11
【问题描述】:

我有一个对象列表,这些对象除了类型之外具有所有相同的字段。我想在呈现此类项目之前在 ng-repeat 中显示一个字幕。现在我有 x 种类型的项目的 x ng-repeats 并且它变得难以管理。除了字幕之外,这些块都是相同的。假设范围数组没有分散的类型,它们按其类型细分。例如,当渲染时,我想显示这个。

渲染

Cats
cat 1
cat 2
cat 3

Dogs
dog 1
dog 2
dog 3

Lizards
lizard 1
lizard 2
lizard 3

型号

$scope.animals = [
  { name: "cat 1", type: "cat" },
  { name: "cat 2", type: "cat" },
  { name: "cat 3", type: "cat" },
  { name: "dog 1", type: "dog" },
  { name: "dog 2", type: "dog" },
  { name: "dog 3", type: "dog" },
  { name: "lizard 1", type: "lizard" },
  { name: "lizard 2", type: "lizard" },
  { name: "lizard 3", type: "lizard" }
];

查看

<div ng-repeat="animal in animals">
  <!-- if first animal type appearing show subtitle -->
  {{animal.name}}
</div>

我不想像现在这样构造我的数据并渲染冗余的 ng-repeats。

型号

$scope.cats = [
 ...
];
$scope.dogs = [
 ...
];
$scope.lizards = [
 ...
];

查看

<h2>Cats</h2>
<div ng-repeat="cat in cats">
  {{cat.name}}
</div>

<h2>Dogs</h2>
<div ng-repeat="dog in dogs">
  <h2>Dogs</h2>
  {{dog.name}}
</div>

<h2>Lizards</h2>
<div ng-repeat="lizard in lizards">
  {{lizard.name}}
</div>

提前致谢!

【问题讨论】:

    标签: angularjs angularjs-ng-repeat ng-repeat


    【解决方案1】:

    您需要检查类型是否与之前的类型不同。您可以使用$index - 1获取此项目

       <div ng-repeat="animal in animals">
          <h1 ng-if="animal.type != animals[$index - 1].type">
            {{ animal.type }}
          </h1>
          {{animal.name}}
        </div>
    

    【讨论】:

    • @osi,我注意到您在回答中忘记了某些内容,因此我冒昧地“修复”了它。
    【解决方案2】:

    尝试访问ng-repeatloop 的前一个元素并将其类型与当前元素的类型进行比较。如果类型不同,您必须显示您的字幕。

    查看question 了解如何获取前一个元素。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多