使用ng-if选择ng-repeat循环中的第二项

时间:2016-02-06 09:32:52

标签: javascript angularjs

我正在开发一个页面,它遍历一堆内容,并在白天对它们进行排序/分组。分组工作,但我想在循环中的前两个项目与其余项目不同。我尝试使用ng-ifng-if="$first || $index == 1"在下面的代码示例中使用ng-if="!$first || !$index != 1",但似乎并没有这样做。

ng-repeat循环中选择第一项和第二项的正确方法是什么?

<div class="col-sm-12 day-block" ng-repeat="(key,value) in article.items | groupBy:'posted|date: MMM:dd' | toArray:true ">
  <div class="col-sm-2 timestamp">
    <h3>March 9</h3>
    <h1>Day 4</h1>
  </div>
  <div class="col-sm-10" ng-repeat="article in value | orderBy:'posted' | unique: 'nid'">
      <div class="col-sm-12">
        <div class="row">
          <div class="col-xs-6" ng-if="$first || $index == 1">
            <span ng-class="blog-post-thumbnail" ng-bind-html="to_trusted(article.main_image)"></span>
            <h2 ng-bind-html="to_trusted(article.node_title)"></h2>
            <h4 ng-bind-html="to_trusted(article.author)"></h4>
            <h4 ng-bind-html="to_trusted(article.posted)"></h4>
          </div>
        </div>

      <div class="row" ng-if="!$first || $index != 1">
        <div class="col-xs-4">
          <span ng-class="blog-post-thumbnail" ng-bind-html="to_trusted(article.main_image)"></span>
        </div>

        <div class="col-xs-8">
          <h3 ng-bind-html="to_trusted(article.node_title)"></h3>
          <h4 ng-bind-html="to_trusted(article.author)"></h4>
        </div>
      </div>
    </div>
  </div>
</div>

1 个答案:

答案 0 :(得分:2)

对于除1之外的所有索引,您的表达式ng-if="!$first || !$index == 1将为真。 要选择1st2nd,您可以尝试:ng-if="$index == 0 || $index == 1"

对于其他人,您可以尝试ng-if="!($index == 0 || $index == 1)"