Search code examples
javascripthtmlcssangularjsangularjs-ng-repeat

How to apply border-bottom to the last repeated same value in ng-repeat template using angularjs or javascript?


I have the following code. I want to apply the border-bottom to the category (i.e at last category of same or repeated value) in ng-repeat. If I run this code, I am getting the border-bottom for all categories, but I don't want like that. I need to apply to the last repeated or same value of category.

html:

<body ng-app="app" ng-controller="Ctrl">
  <div  ng-repeat="item in categorycount[0].vals">
    <div ng-class="{'border-class':item.category.length}">
      <span >{{item.category}}</span>
      <span>{{item.description}}</span>
    </div>
  </div>
</body>

js:

var app = angular.module('app', []);
app.controller('Ctrl', function($scope,$rootScope) {

  $scope.categorycount = [
  {
    name: 'ABC',
    vals: [
      { description: 'first description', category: 'FIRST'},
      { description: 'second description', category: 'SECOND'},
      { description: 'third description', category: 'SECOND'},
      { description: 'fourth description', category: 'SECOND'},
      { description: 'fifth description', category: 'THIRD'},
      { description: 'sixth description', category: 'THIRD'},
      { description: 'seventh description', category: 'THIRD'},
      { description: 'eighth description', category: 'THIRD'},
      { description: 'ninth description', category: 'FOURTH'},
      { description: 'tenth description', category: 'FOURTH'},
    ],
  },
];

let result={};

$scope.categorycount[0].vals.forEach(ob => {
  if(result[ob.category]){
    result[ob.category]=result[ob.category]+1;
    } else {
    result[ob.category]=1;
    }
  });
  $rootScope.categoryPropertyLength = result;
  console.log(result);//{FIRST: 1, SECOND: 3, THIRD: 4, FOURTH: 2}

});

css:

.border-class{
  border-bottom: 1px solid black;
}

I am thinking that I am failing to write some condition in template. Please help me to get this solution.

Created Plnkr.

Current Output:

enter image description here

Expected Output:

enter image description here


Solution

  • You can try with this condition:

    ng-class="{'border-class': ($index == categorycount[0].vals.length - 1) || categorycount[0].vals[$index+1].category != item.category}"
    

    Basically adds the border if it's the last element OR if the following element has a different category, assuming the list is sorted by category.