Reputation: 2180
Hi I'm beginner in Angular. I am facing a problem with using date comparison with orderBy
filter. The problem is that filter does not consider month and year. Here are the code snippets (also available on fiddle)
SCRIPT
var list = [
{
name: 'Jon',
joining_date:'23/10/2015',
age: 23
}, {
name:'Viki',
joining_date:'24/01/2015',
age: 20
}, {
name: 'Abc',
joining_date:'25/10/2015',
age: 43
}, {
name: 'XYZ',
joining_date:'28/10/2015',
age: 21
}
];
var empApp = angular.module('emp-list', []);
empApp.controller('emp-table',function($scope){
$scope.data = list;
})
HTML
<div ng-app="emp-list">
<div class="search-box">
<input type="text" ng-model="searchKeyword"></input>
</div>
<div ng-controller="emp-table">
<table width="100%">
<tr>
<th width="33%">Name</th>
<th width="33%">Joining Date</th>
<th width="33%">Age</th>
</tr>
<tr ng-repeat="lists in data | filter: searchKeyword | orderBy : 'joining_date'">
<td>{{lists.name}}</td>
<td>{{lists.joining_date}}</td>
<td>{{lists.age}}</td>
</tr>
</table>
</div>
</div>
RESULT
Name Joining Date Age
Jon 23/10/2015 23
Viki 24/01/2015 20
Abc 25/10/2015 43
XYZ 28/10/2015 21
Upvotes: 2
Views: 97
Reputation: 2180
I got one more solution without changing my json data.. please check my code below.
I just created a following function which will convert dates from string to date format
$scope.dateFormate = function(joinDate){
return new Date(joinDate)
}
SCRIPT
var list = [{
name: 'Jon',
joining_date:'2015-10-23',
age: 23
},
{
name:'Viki',
joining_date:'2015-01-24',
age: 20
},
{
name: 'Abc',
joining_date:'2015-10-25',
age: 43
},
{
name: 'XYZ',
joining_date:'2015-10-21',
age: 21
}];
var empApp = angular.module('emp-list', []);
empApp.controller('emp-table',function($scope){
$scope.data = list;
$scope.dateFormate = function(joinDate){
return new Date(joinDate)
}
})
Upvotes: 0
Reputation: 2745
This is because your joining_date
is a string instead of Date
object. As the result orderBy
compares them as strings. Here is your fixed example: https://jsfiddle.net/bocn0vrb/1/.
You can also use a custom function for comparing those strings with some casting. Take a look at documentation page: https://docs.angularjs.org/api/ng/filter/orderBy.
Upvotes: 1