Different class for the last element in ng-repeat

前端 未结 6 2050
情话喂你
情话喂你 2020-12-04 12:01

I am creating a list using ng-repeat something like this

  
{{file.name}}

But for

相关标签:
6条回答
  • 2020-12-04 12:11

    It's easier and cleaner to do it with CSS.

    HTML:

    <div ng-repeat="file in files" class="file">
      {{ file.name }}
    </div>
    

    CSS:

    .file:last-of-type {
        color: #800;
    }
    

    The :last-of-type selector is currently supported by 98% of browsers

    0 讨论(0)
  • 2020-12-04 12:12

    To elaborate on Paul's answer, this is the controller logic that coincides with the template code.

    // HTML
    <div class="row" ng-repeat="thing in things">
      <div class="well" ng-class="isLast($last)">
          <p>Data-driven {{thing.name}}</p>
      </div>
    </div>
    
    // CSS
    .last { /* Desired Styles */}
    
    // Controller
    $scope.isLast = function(check) {
        var cssClass = check ? 'last' : null;
        return cssClass;
    };
    

    Its also worth noting that you really should avoid this solution if possible. By nature CSS can handle this, making a JS-based solution is unnecessary and non-performant. Unfortunately if you need to support IE8> this solution won't work for you (see MDN support docs).

    CSS-Only Solution

    // Using the above example syntax
    .row:last-of-type { /* Desired Style */ }
    
    0 讨论(0)
  • 2020-12-04 12:14

    You can use $last variable within ng-repeat directive. Take a look at doc.

    You can do it like this:

     <div ng-repeat="file in files" ng-class="computeCssClass($last)">
     {{file.name}}
     </div>
    

    Where computeCssClass is function of controller which takes sole argument and returns 'last' or null.

    Or

      <div ng-repeat="file in files" ng-class="{'last':$last}">
      {{file.name}}
      </div>
    
    0 讨论(0)
  • 2020-12-04 12:17
    <div ng-repeat="file in files" ng-class="!$last ? 'class-for-last' : 'other'">
       {{file.name}}
    </div>
    

    That works for me! Good luck!

    0 讨论(0)
  • 2020-12-04 12:23

    The answer given by Fabian Perez worked for me, with a little change

    Edited html is here:

    <div ng-repeat="file in files" ng-class="!$last ? 'other' : 'class-for-last'"> {{file.name}} </div>

    0 讨论(0)
  • 2020-12-04 12:24

    You could use limitTo filter with -1 for find the last element

    Example :

    <div ng-repeat="friend in friends | limitTo: -1">
        {{friend.name}}
    </div>
    
    0 讨论(0)
提交回复
热议问题