Tutorials for web designers and developers
Tutorials for Developers_
Search
Close this search box.

Tutorial 7: Using filters in AngularJS service | AngularJS Filters

Hafiz Faraz Mukhtar

Hafiz Faraz Mukhtar

Hafiz Faraz Mukhtar is an expert Web Developer, SEO specialist, and Graphic Designer. Hafiz Faraz is an expert in WordPress design and development. Hire on Upwork | Hire on Fiverr

 

AngularJS-filters

AngularJS lets you organize data, so that it only shows up something if it meets certain criteria. It does through something called AngularJS filters. Filters in angularjs transforms the data as it passes from the scope to the directive but it doesn’t change the source data, allowing you to flexibly format or transform data for display in views. We can use filters in angularjs with expressions or to modify the information from our models.Now the easiest way to understand how filters in angularjs works is to add them in expressions.

We will make use of previous tutorial files in which we created a guitar list app(Download last tutorial project files) whose end result looks like this:

  1. For this tutorial, you need to update ‘data.json’ file that we used in previous tutorial (simple copy and replace code in data.json with the following):
    [
    		{
    			"name" 		 : "Acoustic Guitar",
    			"description": "Acoustic, electro-acoustic and classical guitars, from leading brands.",
    			"image"	:  "Acoustic",
    			"price" : "23.78",
    			"dateAdded" : "1403926823000",
    			"category" : "expensive"
    		},
    		{
    			"name" 		 : "Electric Guitar",
    			"description": "Ever-popular solid-body guitars, to hollow-body guitars and archtops.",
    			"image"	:  "Electric",
    			"price" : "18.34",
    			"dateAdded" : "1399779623000",
    			"category" : "expensive"
    		},
    		{
    			"name" 		 : "Bass Guitar",
    			"description": "Classic Fender Bass, Precision and Jazz basses, to Gibson Thunderbirds.",
    			"image"	:  "Bass",
    			"price" : "35.98",
    			"dateAdded" : "1402544423000",
    			"category" : "cheap"
    		}
    ]
  2. Also you need to REPLACE style.css file in project by this code: Download styles.css here
  3. Now open index.html file (created in previous tutorial), i can easily add filter like an ‘uppercase‘ filter that will show us GUITAR NAMES in uppercase using this code:
    <!doctype html>
    <html ng-app="GuitarApp">
    <head>
    	<meta charset="UTF-8">
    	<title>Angular Application</title>
    	<link rel="stylesheet" type="text/css" href="styles.css"></link>
    	<link href='http://fonts.googleapis.com/css?family=PT+Serif:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
    	<script src="lib/Angular/angular.min.js" type="text/javascript" ></script>
    	<script src="js/controllers.js" type="text/javascript" ></script>
    </head>
    <body>
    
    <!-- Start of Controller -->	
    <div class="main" ng-controller="GuitarFunction">
     <!-- SEARCH AREA -->
    	 <div class="search">
    		<h1>Offshore Guitar Store</h1>
    		<label>Search Guitar</lavel>
    		<input type="text" ng-model="query" >
    	
    		<label>Sort by:
    			<select ng-model="orderGuitar">
    				<option value="name" selected>name</option>
    				<option value="reknown">Reknown</option>
    			</select>
    		</label>
    		<br>
    		<label>
    			<input type="radio" ng-model="direction" name="direction" checked>
    			Ascending
    		</label>
    		<label>	
    			<input type="radio" ng-model="direction" name="direction" value="reverse" >
    			Descending
    		</label>
    	</div>
    	<!--END of SEARCH AREA -->
    
    	<ul> 
    		<li class="itemHolder" ng-repeat="item in guitarVariable">
    		<img ng-src="img/{{item.image}}.jpg">
    			<div>
    				<h3> {{item.name | uppercase }}</h3>
    				<p> {{item.description}}</p>
    			</div>
    		</li>
    	</ul>
    </div>
    
    
    <a class="developer" href="http://blog.hfarazm.com/category/angular-js">« Goto developer's blog </a>
    </body>
    </html>

    Code Explanation:

    • There is a search panel in index.html
    • We added ‘| uppercase‘ next to item.name expression which if loaded in firefox browser will show Guitar Names in Upper Case like this:


    You can see that guitar names are in uppercase. If you have run it in your firefox browser, you might be looking for that price and date (seen in above pic) but it wont show up yet. Lets see how you can add other filters. Also search pannel will not work for now, we shall work on it in next tutorial. But for now just focus on FILTERS only.

[table]Some other useful filters are:

uppercase or lowercase – Change the case of a string (Above example)

currency – Format a currency value
number – Format a general numeric value

json – Generate a JSON representation
date – Format the date
limitTo – Select/Display a limited no. of objects/information from a model(data).
orderBy – Sort the objects in an array

filter – Selects object in an array[/table]

Check documentation at: AngularJS site

Now lets check out above filters one by one:

  • currency:

    To use currency filter you need to have price(I mean any numerical value) of guitars in your data.json file. I’ve already updated the data.json file above. You will find “price” in data.json. We need to show price in our current application. You know how to show price it in index.html(Dont know? check out this tutorial). Lets just ADD the following code in index.html file like this:

    <div>
    	<h3> {{item.name | uppercase }}</h3><p class="rightPrice">{{item.price | currency }}</p>
    	<p> {{item.description}}</p>
    </div>

    Now you will see $ (dollar sign) with price. Secondly,  Item.price is getting price from data.json and | currency is filtering it.

    You can also use it this way for different currency as well.

    {{item.price | currency:"£"  }}
  • number:

    we shall use number filter in price. Basically if you look into data.json file you will see that price is something like  18.34 etc for different guitars. We don’t want to show numbers after that point I mean i want 18.34 to be 18 (round off) or to limit the digits after DOT suppose I want 18.3 instead of 18.34 then at this point number filter is helpful. Lets just ADD this piece of code in above index.html:

    <div>
    	<h3> {{item.name | uppercase }}</h3><p class="rightPrice">{{item.price | number:0 }}</p>
    	<p> {{item.description}}</p>
    </div>

    Now you will see price will be have no tenth value.

    You can also use it this way for different type of values.

    {{item.price | number:1  }}
  • json:

    json will show you exact json formatted data that you find in data.json. Lets just ADD the following piece of code in above index.html file like this:

    <div>
    	<h3> {{item.name | uppercase }}</h3><p class="rightDate">Price Revised on: {{item.dateAdded | date:'dd/MM/yy'}}</p>
            <p class="rightPrice">{{item.price | number:0 }}</p>
    	<p> {{item.description | json}}</p>
    </div>

     

    Now you will see description is formatted in json.

  • date:

    date is tricky (I mean date here 🙂 )we shall use date in milliseconds in our data.json file. Open data.json file and check dateAdded. Basically if you look into data.json file you will see that dateAdded is something like  1403926823000 etc for different guitars. We don’t want to show this date as it looks in data.json  instead we are more interested in readable date. Date from milliseconds will be converted by AngularJS itself. Lets just ADD following piece of code in above index.html file like this:

    <div>
    	<h3> {{item.name | uppercase }}</h3><p class="rightDate">Price Revised on: {{item.dateAdded | date:'dd/MM/yy'}}</p>
            <p class="rightPrice">{{item.price | number:0 }}</p>
    	<p> {{item.description}}</p>
    </div>

    Now you will see ‘price revised on’ in your application.

    You can also use it this way for showing just the day and month.

    {{item.dateAdded | date:'dd-MM'  }}
  • limitTo:

    As the name implies is to limit the amount of information coming. I mean we have three guitars we want to show only 2 to our user and hide the rest of guitars. We can do this by limitTo filter. Lets just add following piece of code in above index.html file like this(This time we add limitTo in ng-repeat directive because it is looping through model and we need to limit that):

    <li class="itemHolder" ng-repeat="item in guitarVariable | limitTo:2 ">

    Now you will see only two guitars in your application.

  • orderBy:

    It sorts the information in an given order. Lets just add following piece of code in above index.html file like this(This time it will order guitars list with respect ascending order of their prices):

    <li class="itemHolder" ng-repeat="item in guitarVariable | orderBy:'price' ">

    You can also use it this way for ordering guitars in descending order.

    <li class="itemHolder" ng-repeat="item in guitarVariable | orderBy:'-price' ">
  • filter:

    It filters out the information and displays relevant content only. Lets just add following piece of code in above index.html file like this(This time it will order guitars list with respect to ascending order of their prices):

    <li class="itemHolder" ng-repeat="item in guitarVariable | filter:{category: 'cheap'}">

     

    You can also use it this way for showing only EXPENSIVE guitarsin your application.

    <li class="itemHolder" ng-repeat="item in guitarVariable | filter:{category: 'expensive'}">

Update RANDOM FILTER IN ANGULARJS

if you want to filter randomly the array elements from JSON ( or shuffle in angularJS )then here is how you can do it: just goto result and click random button to see the list changes randomly

this update is by Oğuzhan Oya

Download Project Files

Hope you like it. Please share my work.

next-AngularJS MVCPrevious-Chapter-Button

//

38 Responses

  1. thanks a lot………..they really hepls a lot……………

    only problm is we have tw wait a lot for next lecture :

  2. Thanks alot bro , it’s more than i need , and it will be good if you can tell me how to get data from mysql using angular

  3. thanks a lot………..they really hepls a lot……………

    only problm is we have tw wait a lot for next lecture :

  4. thanks a lot………..they really hepls a lot……………

    only problm is we have tw wait a lot for next lecture :

  5. Thanks alot bro , it’s more than i need , and it will be good if you can tell me how to get data from mysql using angular

  6. Thanks alot bro , it’s more than i need , and it will be good if you can tell me how to get data from mysql using angular

  7. hey hafiz, i got stuck in an assignment just like yours at my collage. cannot figure it out how to call json data as well as images and pressing the next button will change the image and data will changes. i am asking you a favor if you could solve my issues would be a great help. let me know then i can submit it to you. thank you!

  8. hey hafiz, i got stuck in an assignment just like yours at my collage. cannot figure it out how to call json data as well as images and pressing the next button will change the image and data will changes. i am asking you a favor if you could solve my issues would be a great help. let me know then i can submit it to you. thank you!

Leave a Reply

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