突出显示 Angular JS 中的过滤行

Highlight filtered rows in Angular JS

本文关键字:过滤 JS 显示 Angular      更新时间:2023-09-26

>我有一个需要突出显示重复值的数组。这就是我到目前为止所拥有的..

.HTML

<tr ng-repeat="x in names | unique: 'names'" >
   <td>  {{ x }} </td>
</tr>
<style>
.duplicate{
background: yellow;
}
</style>

控制器:

 angular.module('myApp', []).controller('nameCtrl', function($scope) {
            $scope.names = [
                'Bob',
                'Dan',
                'Philip',
                'Philip',
            ];
        });

编辑:在上面的示例中,"Philip"将被突出显示并具有duplicate

你可以这样实现它:

<div ng-app="MyApp">
  <div ng-controller="MyController">
    <table>
      <tr ng-repeat="name in names | unique">
        <td ng-class="{ 'duplicate': names.indexOf(name) !== names.lastIndexOf(name) }">{{name}}</td>
      </tr>
    </table>
  </div>
</div>

这会将 duplicate 类应用于indexOf返回的值与lastIndexOf不同的元素。这只能发生在数组中多次的项目上。

JSFiddle可在此处获得。

如果您不想过滤掉重复项,可以使用以下内容:

<div ng-app="MyApp">
  <div ng-controller="MyController">
    <table>
      <tr ng-repeat="name in names track by $index">
        <td ng-class="{ 'duplicate': names.indexOf(name) !== names.lastIndexOf(name) }">{{name}}</td>
      </tr>
    </table>
  </div>
</div>

我认为这应该有效。

<tr ng-repeat="(key, count) in names | count" >
  <td ng-class="{your-highlight-class: count > 1 }">  {{ key }} </td>
</tr>
app.filter('count', function ( ) {
  return function (collection) {
    var result = {};
    collection.forEach( function( elm ) {
      if(!result[elm]) {
        result[elm] = 0;
      }
      result[elm]++;
    });
    return result;
  }
}]);