[英]Sorting a list of json objects in angularjs on click of button
我試圖在其中一個屬性是“日期”字段的json對象的嵌套列表上排序。 日期字段采用MM/dd/yyyy
格式。
這是HTML代碼:
<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>
//這是腳本:
<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>
單擊按鈕時,列表未正確排序。
我已經為orderBy過濾器引用了Angular文檔: https ://docs.angularjs.org/api/ng/filter/orderBy
這是我為上述情況創建的plunker: https ://plnkr.co/edit/Q1m24arssRxC6B3NNO0n?p = preview
對此有何幫助?
在你的html中調用正確的函數:
<button type="button" ng-click="testCtrl.sortList()">Test Button</button>
並訂購正確的屬性名稱:
vm.sortList = function () {
vm.listToBeDisplayed = orderBy(empList, 'joinDate', true);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.