【问题标题】:Angular apply style to the first visible item in ngRepeatAngular 将样式应用于 ngRepeat 中的第一个可见项目
【发布时间】:2016-03-05 20:47:39
【问题描述】:

我有一个由 ngRepeat 生成的列表,就像这样

<ul class="list-group">
    <li class="list-group-item" ng-repeat="data in tree | filter:key">
        {{data.name}}
    </li>
</ul>

我希望列表中的第一项具有圆角。我有这样的风格

.first-item {
  border-top-left-radius: 15px;
  border-top-right-radius: 15px;
}

如何将此样式应用于第一个可见项?请注意,key 连接到搜索框,因此第一项是动态的。

【问题讨论】:

  • 使用 CSS 和 :first-child 选择器可能更容易处理。
  • @Stubb0rn 你是对的!我应该想到这一点,但我想我的大脑有棱角。我还假设过滤器使用“display:none”工作......但它没有。

标签: css angularjs angularjs-ng-repeat


【解决方案1】:

使用 $first,表示 ng-repeat 中的第一次迭代

<ul class="list-group">
    <li ng-class="{'first-item':$first}"
class="list-group-item" ng-repeat="data in tree | filter:key">
        {{data.name}}
    </li>
</ul>      

编辑:由于first-item 有一个破折号,它必须用引号引起来

【讨论】:

  • @SasiKiran 是的。有用。谢谢。但我还必须将班级中的边框更改为 !important。与引导 css 中的另一个类存在冲突。这就是为什么我更喜欢 Bastien 的回答。
【解决方案2】:

使用 $first 和 ng-class。 $first 是在本地范围内公开的属性,用于重复列表中的每个项目。如果该项目是重复列表中的第一个,则其值为 true。 HTML 应如下所示:

<ul class="list-group">
<li class="list-group-item" ng-repeat="data in tree | filter:key" ng-class="{'.first-item': $first}">
    <div>{{data.name}}</div>
</li>

【讨论】:

    【解决方案3】:

    您可以使用 $index 变量值在 ng-repeat 中进行此类条件格式化。这是一个例子:

    <ul class="list-group">
        <li class="list-group-item" 
            ng-repeat="data in tree | filter:key" 
            ng-class="{'first-item': $index == 0}">
            {{data.name}}
        </li>
    </ul>
    

    【讨论】:

      【解决方案4】:

      Pure Angular Way 是:

      <ul class="list-group">
          <li class="list-group-item" ng-repeat="data in tree | filter:key track by $index" ng-class="{MyClassName: $index == 0}">
              {{data.name}}
          </li>
      </ul>
      

      或查看 Sasi Kiran 的回答 ;)

      【讨论】:

        【解决方案5】:

        你可以使用css规则first-child:

        .list-group li:first-child { 
             border-top-left-radius: 15px;
             border-top-right-radius: 15px;
        }
        

        http://www.w3schools.com/cssref/sel_firstchild.asp

        【讨论】:

        • 这是唯一适合我的解决方案。使用ng-class="{'first-item':$first}" 对我不起作用,因为引导程序已经有一个选择器.list-group-item:first-child,这显然更具体。
        猜你喜欢
        • 2015-01-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-09-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多