AngularJs始终将范围数组保持在排序状态

时间:2015-08-01 12:26:33

标签: angularjs

我需要通过updated_at(linux时间戳,数组开头的最新元素)实际排序$ scope.array。我怎么能这样做? $ scope.array有时可能会有变化,我需要始终将此数组保持在已排序状态。



$scope.array = [{updated_at: 1438405112}, {updated_at: 1438405110}, {updated_at: 1438405102}];

$scope.array2 = [{updated_at: 1438105112}, {updated_at: 1438205110}, {updated_at: 1438405104}];

$scope.array = $scope.array.concat($scope.array2);      


$scope.$watch('array', function(newValue) { 
 $scope.array = $filter('orderBy')($scope.array, 'updated_at'); 
}, true);




1 个答案:

答案 0 :(得分:0)

您的代码通常对我来说很好,我看到的唯一可能导致问题的是行

$scope.array = $filter('orderBy')($scope.array, 'updated_at'); 

此行每次都可能生成一个新数组并将其分配给范围。结果,$watch函数再次被触发,因为值"已更改" ..

您想要的是一种不会创建新数组但会更改现有数组的排序。

这是我的傻瓜做你想做的事情

http://plnkr.co/edit/TP5mzA40m77lS5gCbRfT?p=preview

angular.module('myApp').controller('MyCtrl', function($scope){

  $scope.awesomeThings = ['c','b','a'];

  $scope.add = function(str){
    $scope.awesomeThings.push(str);
  }

  $scope.$watch('awesomeThings', function(){
    $scope.awesomeThings.sort();
  }, true);

});

正如您所看到的,我在数组上使用.sort()函数,而我不会将其分配回范围。

我必须声明这有点贵。你可能只想编写一个名为"排序列表"的新数据结构。它只是以排序的方式进行CRUD。

这是我在网上找到的解决方案:https://github.com/shinout/SortedList

如何按时间戳

对对象进行排序

这是如何使用.sort按时间戳

对对象进行排序的方法

http://plnkr.co/edit/IHpK6jv8izzDMEffUz9x?p=preview

var $scope = {};
$scope.array = [{updated_at: 1438405112}, {updated_at: 1438405110}, {updated_at: 1438405102}];
$scope.array2 = [{updated_at: 1438105112}, {updated_at: 1438205110}, {updated_at: 1438405104}];
$scope.array = $scope.array.concat($scope.array2);     


var ASC = 1;
var DESC = -1;

var sortOrder = ASC;

$scope.array.sort(function(a,b){
  return sortOrder * ( a.updated_at - b.updated_at );

});

console.log($scope.array);
document.write('<pre>' + JSON.stringify($scope.array,{},4) + '</pre>');