Reputation: 1003
I am trying to sort a nested list of json objects on one of the properties of which is a "date" field. The date field is in MM/dd/yyyy
format.
This is the HTML code:
<body ng-app="Test" ng-controller="TestController as testCtrl" ng-init="testCtrl.displayList()">
<ul ng-repeat="de in testCtrl.listToBeDisplayed">
<li >{{ de.empId }} {{ de.empName }} {{ de.joinDate }}</li>
</ul>
<button type="button" ng-click="testCtrl.sortList()">Test Button</button>
// This is the script:
<script>
angular.module("Test",[]);
angular.module("Test").controller("TestController",TestController);
TestController.$inject = ['orderByFilter','$filter'];
function TestController(orderBy,$filter){
vm = this;
vm.demoList = [
{
"Employees" :
[{
"id" : "1001",
"name": "Andre",
"date": "05/20/2016"
},
{
"id" : "1002",
"name": "Chris",
"date": "04/11/2016"
},
{
"id" : "1003",
"name": "Darren",
"date": "03/11/2016"
},
{
"id" : "1004",
"name": "Marlen",
"date": "08/11/2016"
}]
}
];
propertyName = 'date';
vm.displayList = function(){
console.log("in display List fn");
empList=[];
for(var i=0;i<vm.demoList[0].Employees.length;i++)
{
value = vm.demoList[0].Employees[i];
console.log("value="+value);
var employee = {
empId: '',
empName: '',
joinDate: ''
};
employee.empId = value.id;
employee.empName = value.name;
employee.joinDate = $filter('date')(new Date(value.date), "MM/dd/yyyy");
empList[i] = employee;
}
vm.listToBeDisplayed = empList;
}
</script>
</body>
When I click the button, the list is not getting sorted properly.
I have referred Angular documentation for orderBy filter: https://docs.angularjs.org/api/ng/filter/orderBy
This is the plunker I created for the above situation: https://plnkr.co/edit/Q1m24arssRxC6B3NNO0n?p=preview
Any help on this ?
Upvotes: 1
Views: 717
Reputation: 855
Call the correct function in your html:
<button type="button" ng-click="testCtrl.sortList()">Test Button</button>
And order on correct property name:
vm.sortList = function () {
vm.listToBeDisplayed = orderBy(empList, 'joinDate', true);
}
Upvotes: 0