简体   繁体   中英

AngularJS add conditional class in ng-repeat

I'm working with some AngularJS ng-repeat looping, but I want to generate the markup of a grid, but need to add a 'grid--last' class to the 4th item in the grid, is this achievable?

My HTML:

<div ng-repeat="service in services" class="grid__4">
                <div class="services__box">
                    <img src="img/services/{{service.thumb}}.jpg" alt="" class="services__box__img">
                    <h1 class="services__box--alpha alpha">{{service.title}}</h1>
                    <p>
                        {{service.text}}
                    </p>
                    <a href="{{service.url}}.php" class="services__box--btn btn btn--blue">{{service.button}}</a>
                </div>
            </div>

Ideally I need to get the index of the array and use ng-class. Can anybody shed some light as to how I could do this? Thanks!

ng-class="{}"

Angular repeat scope provide an $index property; therefore, you can do data-ng-class="{'grid--last': $index == 3}" assuming you mean that 4th item is 3 since index start at 0.

You can do this with CSS, but there may be browser compatibility issues with IE8 and lower (shocking)

plnk here

relevant code:

<style>
      li.item {
        background-color:blue;
      }

      li.item:last-child {
       background-color: red;
      }
    </style>
  </head>

  <body ng-controller="testCtl">
    <ul>
      <li class="item" ng-repeat="val in [1, 2, 3, 4]">{{val}}</li>
    </ul>
  </body>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM