使用 orderBy 在 ng-repeat 中突出显示新元素

Highlight new element in ng-repeat with orderBy

我有一个简单的列表(json 数据来自服务器)但在示例中我只是将数据添加到局部变量中并将其呈现到 <table> 中。我想将新项目添加到列表中并用突出显示 cell.Problem 向用户显示新项目是我用 orderBy 订购列表所以我不知道新添加元素的位置。

简单列表数据

$scope.options = [
    {'title' : 'Title1', 'label' : 'Zip code', 'type' : 'xxx' },
    {'title' : 'Title2', 'label' : 'MD', 'type' : 'title1'},
    {'title' : 'Title3', 'label' : 'DMS', 'type' : 'title2'}
];

控制器:

function Ctrl($scope) {
  $scope.options = [
    {'title' : 'Title1', 'label' : 'Zip code', 'type' : 'xxx' },
    {'title' : 'Title2', 'label' : 'MD', 'type' : 'title1'},
    {'title' : 'Title3', 'label' : 'DMS', 'type' : 'title2'}
];
  $scope.addOptions = function(op){
    $scope.options.push(angular.copy(op));
  };
}

HTML:

<div ng-controller="Ctrl">
  <table border="1">
  <tr ng-repeat="option in options| orderBy:'title'">
    <td>{{option.title}}</td>
    <td>{{option.label}}</td>
    <td>{{option.type}}</td>
  </tr>
  </table>
  <input type="text" id="name" name="name" ng-model="item_add.title" /><br>
  <input type="text" id="name" name="name" ng-model="item_add.label" /><br>
  <input type="text" id="name" name="name" ng-model="item_add.type" /><br>
  <input type="button" value="Add" ng-click="addOptions(item_add)"/>
</div>

简单的 Plunker:- http://plnkr.co/edit/3rOgopGompRBFruLAZC4?p=preview

您可以在范围内再添加一个值以区分新行并为其应用样式。

HTML

<table border="1">
  <tr ng-repeat="option in options| orderBy:'title'" ng-class="{'newitem':option.newlyAdded}">
    <td>{{option.title}}</td>
    <td>{{option.label}}</td>
    <td>{{option.type}}</td>
  </tr>
  </table>

JS

  $scope.addOptions = function(op){
    op.newlyAdded = true;
    $scope.options.push(angular.copy(op));
  };

演示:http://plnkr.co/edit/1eZneQwzRWLubcjNnBln?p=preview

你可以用老式的方式来做,循环遍历你的项目并取消设置某个 fresh 标志并仅为你的新项目设置它。

Here's an updated Plunk.

addOptions 变为:

  $scope.addOptions = function(op){
    angular.forEach($scope.options, function(opt) {
      opt.fresh = false;
    })
    var newOpt = angular.copy(op);
    newOpt.fresh = true;
    $scope.options.push(newOpt);

  };

模板更新(添加了 ng-class):

  <tr ng-repeat="option in options| orderBy:'title'" ng-class="{fresh: option.fresh}">
    <td>{{option.title}}</td>
    <td>{{option.label}}</td>
    <td>{{option.type}}</td>
  </tr>