Search code examples
angularjsjsonangularjs-orderby

AngularJS order by date is not working


I am trying to order my json by the date given in the json object, but it only checks on the first digits, example: 19-08-2017 it only checks 19 and ignores -08-2017.

This is my json:

$scope.tasks = [{
    "id" : 1,
    "taskDescription" : "Afspraak | Overleg planning/projecten met RT",
    "taskUser" : "Kenneth Clark",
    "taskDate" : "02-07-2017",
    "taskStart" : "14:00",
    "taskStop" : "15:00",
    "taskPlannedHours" : "01:00",
    "taskUsedHours" : "01:00",
    "taskChecked" : true
},{
    "id" : 2,
    "taskDescription" : "Al iets gehoord van de opkoper van de VW up!",
    "taskUser" : "Richard Todd",
    "taskDate" : "03-07-2017",
    "taskStart" : "14:00",
    "taskStop" : "15:00",
    "taskPlannedHours" : "01:00",
    "taskUsedHours" : "01:50",
    "taskChecked" : true
},{
    "id" : 3,
    "taskDescription" : "RS6 's Ochtends naar circuit",
    "taskUser" : "Peter Mol",
    "taskDate" : "19-08-2017",
    "taskStart" : "14:00",
    "taskStop" : "15:00",
    "taskPlannedHours" : "01:00",
    "taskUsedHours" : "00:00",
    "taskChecked" : false
},{
    "id" : 4,
    "taskDescription" : "Afspraak | doe ff afspraakje maken",
    "taskUser" : "Robert Vliek",
    "taskDate" : "14-09-2017",
    "taskStart" : "10:00",
    "taskStop" : "12:00",
    "taskPlannedHours" : "02:00",
    "taskUsedHours" : "00:00",
    "taskChecked" : false
}];

This is my code:

<div class="tableRow taskItem" ng-repeat="task in tasks | orderBy:'taskDate':true">

This is the output:

the output


Solution

  • Solution 1:

    If you could change the date format from your data, using yyyy-mm-dd would work.

    Solution 2:

    (if you cant change the date format), you could do:

    <div class="tableRow taskItem" ng-repeat="task in tasks | orderBy: myCustomDateField: true">
    

    and in controller:

    $scope.myCustomDateField = function(item) {
        var parts = item.taskDate.split('-');
        var number = parseInt(parts[2] + parts[1] + parts[0]);
        return number;
    };