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.
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
- AngularJS : Updating a Label Dynamically with User Input
- AngularJS : Text Suggestions
- AngularJS : Sorting objects on various attributes
- AngularJS : Fetching data from the server
- AngularJS : Multiple Views, Layout Template and Routing
- AngularJS : Implementing Routes And Multiple Views
- Building Intuitive Frontend Interfaces with AngularJS