0

Why the following code doesn't sort by date?

http://jsfiddle.net/eliaweiss/1cs3xbtd/1/

html

<div ng-app>
    <script type="text/javascript" src="http://code.angularjs.org/1.0.1/angular-1.0.1.js"></script>
    <div ng:controller="Main">
      <div ng:repeat="(id, i) in items | orderBy:'date'">{{id}}: {{i.date | date}}</div>
    </div>
</div>

js

function Main($scope) {
    $scope.items = {
        0: {date: new Date('12/23/2013')},
        1: {date: new Date('12/23/2011')},
        2: {date: new Date('12/23/2010')},
        3: {date: new Date('12/23/2015')}
    };
}
ryanyuyu
  • 6,366
  • 10
  • 48
  • 53
Elia Weiss
  • 8,324
  • 13
  • 70
  • 110
  • Possible duplicate of [dates not properly sorted in Angular.js](http://stackoverflow.com/questions/21023052/dates-not-properly-sorted-in-angular-js) – Elia Weiss Jun 20 '16 at 11:56
  • I am pretty sure I ran into something similar to this and found that the order by does not work with objects. – Tim Jun 20 '16 at 11:57

2 Answers2

3

Issue is very simple .... javascript objects are not ordered and orderBy therefore only works for arrays

Change model structure to array

charlietfl
  • 170,828
  • 13
  • 121
  • 150
1

What charlietfl says:

JS:

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.items = [
    {
        id: 0,
        date: new Date('12/23/2013')
    },
    {
        id: 1,
        date: new Date('12/23/2011')
    },
    {
        id: 2,
        date: new Date('12/23/2010')
    },
    {
        id: 3,
        date: new Date('12/23/2015')
    }];
})

HTML:

<div ng-app="myApp" ng-controller="myCtrl">
  <div ng:repeat="i in items | orderBy:'date'">{{i.id}}: {{i.date | date}}</div>
</div>
Keugels
  • 790
  • 5
  • 15