Ng-Repeat添加新项目到最后

时间:2016-04-25 10:19:05

标签: javascript angularjs angularjs-ng-repeat ng-repeat

我有ng-repeat页面。类似的东西:

<div class="full-row" ng-repeat="row in pendingRequests | partition:3 track by $index">
                      <div class="one-third" ng-repeat="request in row track by request.id" ng-mouseenter="EnterRequest(request)" ng-mouseleave="LeaveRequest(request)">
                      ...

对于pendingRequests的新集合,每分钟都有新的服务器请求。当服务器返回1分钟后,pendingRequests新项目的新集合将添加到ng-repeat块的末尾,即使此新项目是从服务器返回的集合中的第一个。

如何在ng-repeat块中设置新的/添加的项目? 我发现的类似问题是关于unshift元素的收集。但我有来自服务器的集合,所以我不会手动添加新项目。

2 @Toxantron:

可能,我的问题是因为我有2 ng-repeat而且只有在最后一个转发器中我才使用orderby

<div class="full-row" ng-repeat="row in pendingRequests | partition:3 track by $index">
                          <div class="one-third" ng-repeat="request in row | orderBy: '-modificationDate' track by request.id">

还有代码partition过滤器

app.filter('partition', function() {
    var cache = {};
    var filter = function(arr, size) {
        if (!arr) { return; }
        var newArr = [];
        for (var i=0; i<arr.length; i+=size) {
            newArr.push(arr.slice(i, i+size < arr.length? i+size : arr.length ));
        }
        var arrString = JSON.stringify(arr);
        var fromCache = cache[arrString+size];
        if (JSON.stringify(fromCache) === JSON.stringify(newArr)) {
            return fromCache;
        }
        cache[arrString+size] = newArr;
        return newArr;
    };
    return filter;
});

1 个答案:

答案 0 :(得分:2)

我想你试试orderBy: '-id'

&#13;
&#13;
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
  $scope.requests = [
    { id: 1, name: "Request 1"},
    { id: 2, name: "Request 2"},
    { id: 3, name: "Request 3"},
    { id: 4, name: "Request 4"},
    { id: 5, name: "Request 5"},
    { id: 6, name: "Request 6"}
  ];
});
app.filter('partition', function() {
    var cache = {};
    var filter = function(arr, size) {
        if (!arr) { return; }
        var newArr = [];
        for (var i=0; i<arr.length; i+=size) {
            newArr.push(arr.slice(i, i+size < arr.length? i+size : arr.length ));
        }
        return newArr;
    };
    return filter;
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.js"></script>

<div ng-app="myApp" ng-controller="myCtrl">
  <ol>
    <li ng-repeat="requestRow in requests | orderBy: '-id'|partition: 3">
      <ol>
        <li ng-repeat="request in requestRow" >
          {{ request.name }}
        </li>
      </ol>
    </li>
  </ol>
</div>
&#13;
&#13;
&#13;