AngularJS : Sorting objects on various attributes

21 / Sep / 2012 by raj 1 comments

In last blog on AngularJS, we implemented text suggestions functionality. Now, let’s consider that we have a list of objects with each object having two or more attributes with their corresponding values. The problem is to get the sorted list of objects based on an attribute selected by user at run time. AngularJS provides us a very quick and concise solution to this problem.

[java]
<!Doctype html>
<html ng-app>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js"></script>
<script type="text/javascript">
function FruitsController($scope){
$scope.fruits=[
{name : ‘apple’, size : 10},
{name : ‘banana’, size : 30},
{name : ‘mango’, size : 20},
{name : ‘grape’, size : 2},
{name : ‘peach’, size : 20}
];
}
</script>
</head>
<body>
<div ng-controller="FruitsController">
Sort Fruits By : <select ng-model="selectedFruit">
<option value="name">Name</option>
<option value="size">Size</option>
</select>
<ul>
<li ng-repeat="fruit in fruits | orderBy : selectedFruit">
{{fruit.name + " : "+fruit.size}}
</li>
</ul>
</div>
</body>
</html>
[/java]

In this example, we are dealing with a list of fruit objects each having two attributes- name and size. The attributes and their corresponding values are stored as key value pairs. Thus user can select any of these two attributes at run time and we are supposed to sort the list of fruits in the ascending order of their corresponding values of selected attribute.

In line 19, we used a select box and populated it with two options- name and size. Value of each option stores an attribute name(key). We store the value of the selected option in a variable named “selectedFruit” using the ng-model attribute of AngularJS.

In line 24, we are using ng-repeat to loop over the list of fruit objects and displaying each fruit. However, we are using orderBy function simultaneously and passing it the option value selected from the select box. Thus if user selected “size”, the query becomes orderBy:size and we get a list of fruit objects sorted by attribute “size”.

I will be back with more on AngularJS.
Till then, Have Fun 🙂

Read Further on AngularJS Series

FOUND THIS USEFUL? SHARE IT

comments (1 “AngularJS : Sorting objects on various attributes”)

Leave a Reply

Your email address will not be published. Required fields are marked *