I have lot of records coming from the database. Want to perform sorting based on the priority of the records and vice-versa. My priority is ["H", "M", "L", "NO GO"]. want to show the records based on the priority on-clicking of the button and vice-versa means if first i click need to show the H-M-L-NOGO and toggle clicking should show NO GO-L-M-H. Its not coming perfectly when sorted on priority column. my script.js is
$scope.filterPriority = function () {
if(toggled) {
$scope.peoples.sort(function (a, b) {
return (priorityArray[a.priority] || Infinity ) - (priorityArray[b.priority] || Infinity);
});
$scope.sortBy = 'priority';
$scope.sortDescending = !$scope.sortDescending;
} else {
$scope.peoples.sort(function (a, b) {
return (priorityArray[b.priority] || Infinity ) - (priorityArray[a.priority] || Infinity);
});
$scope.sortBy = 'priority';
$scope.sortDescending = !$scope.sortDescending;
}
toggled = !toggled;
};
/* sorting for remaining columns */
$scope.sortBy = 'name';
$scope.sortDescending = false;
$scope.sort = function(column) {
if ($scope.sortBy === column) {
$scope.sortDescending = !$scope.sortDescending;
} else {
$scope.sortBy = column;
$scope.sortDescending = false;
}
}
My approach in plunker url is https://plnkr.co/edit/HPGnCIRNSdCFU6nI1eO2?p=preview
First the ng-repeat is "p in peoples" and not "peoples in p". Change your priorityArray as shown below. Use the code below, works perfectly:
angular.module('app',[]).controller('mainCtrl', function($scope){
$scope.peoples = [
{
'priority': 'H'},
{
'priority': 'M'},
{
'priority': 'L'},
{
'priority': 'NO GO'},
{
'priority': 'H'},
{
'priority': 'M'
},
];
var priorityArray = { 'H': 1, 'M': 2, 'L': 3, 'NO GO': 4};
var toggled = false;
$scope.filterPriority = function () {
if(toggled){
$scope.peoples.sort(function (a, b) {
return (priorityArray[a.priority] || Infinity ) - (priorityArray[b.priority] || Infinity);
});
}else{
$scope.peoples.sort(function (a, b) {
return (priorityArray[b.priority] || Infinity ) - (priorityArray[a.priority] || Infinity);
});
}
toggled = !toggled;
};
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app='app' ng-controller='mainCtrl'>
<table>
<tr>
<th><a ng-click="filterPriority()">priority</a></th>
<tr ng-repeat="p in peoples"><td>{{p.priority}}</td></tr>
</table>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With