Saturday, November 5, 2016

AngularJS With Examples – Filters

In this article, we'll create our first angularjs application. And hayy!!! its not the traditional Hello World application. :P We are gonna try to build an app which can add, delete members and filter members based on a text. Its very basic, I know.. but its good enough to start with. Lets call our application as FilterApp. We will be using bootstrap CSS for styling purpose. For small applications (especially for learning purpose), I always follow the following app skeleton. Here we will be following the same structure. Feel free to use it in your way. The directory structure will look as

The app root folder is FilterApp. It contains three subfolders
  • css : Contains bootstrap css file and styles.css file where we can add our custom styles if needed.
  • fonts : Contains the fonts for bootstrap.
  • js : Contains all the javascript files. The libraries are included in a separate lib folder within js.
Now create the following files in the folders specified.
  • An html file to describe the layout, FilterApp.html in the root (FilterApp) folder.
  • app.js and controllers.js inside js folder.
So now, we have all the files to start building our first angularjs application. Lets start... Open FilterApp.html using your favourite editor (I prefer Brackets or Notepad++) and add the basic HTML5 layout.
<!doctype html>
<title> Filter a list </title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />
Since bootstrap css is our CSS framework, we need those too. Include the following lines of code within the <head> tag.
<link rel="stylesheet" href="css/bootstrap.min.css">
Add the below line of code just after closing body </body> tag to include angularjs library.
<script src="js/lib/angular.min.js"></script>
OK, now we have to bootstrap our application. ng-app directive is used for this purpose.
Use this directive to auto-bootstrap an AngularJS application. The ngApp directive designates the root element of the application and is typically placed near the root element of the page - e.g. on the <body> or<html> tags. You can have multiple apps within the same page.
In our app, we are using this inside <html> tag.
<html ng-app="FilterApp">
Open app.js and add the following line of code,
var filterApp = angular.module('FilterApp', []);
With this line of code, we actually initialize our app and register the modules on which it depends (specified inside square brackets,here none). Now we have to create a controller which will perform all our logic and initialize the $scope object. The $scope variable connects your controller and views. It holds all the data that will be used within your template. Anything you add to it will be directly accessible in your views. Open controllers.js  and add the following code
var filterAppControllers = angular.module('filterAppControllers', []);

filterAppControllers.controller('MainCtrl', function ($scope) {


filterAppControllers.controller('FilterCtrl', function ($scope) {
$scope.members = ['Google', 'Facebook', 'Microsoft'];

$scope.addMember = function () {
$scope.newMember = '';

$scope.deleteMember = function (item) {
var index = $scope.members.indexOf(item);
$scope.members.splice(index, 1);
Here we have created a module called filterAppControllers and added two controllers MainCtrl and FilterCtrl using .controller method. For FilterCtrl, we have initialised a $scope property named members and added two behaviours addMember and deleteMember to the scope object. Edit the app.js and change it to the following to inject the dependency
var filterApp = angular.module('FilterApp', ['filterAppControllers']);
Now include both app.js and controllers.js in FilterApp.html. For this, add the following line of code after angularjs library inclusion just above closing </html> tag
<script src="js/app.js"></script> <script src="js/controllers.js"></script>
Next, We attach our controller to the DOM using the ng-controller directive.
See that MainCtrl controller is attached to the <body> element. Hence all the properties and behaviour under this scope will be available within the <body>. As of now, we haven't defined anything under MainCtrl (see controllers.js). To make our app more flexible and modular, we have used FilterCtrl within the main controller. A simple header and footer is created using the navbar component provided by bootstrap. Lets divide the code and analyse each part. First of all, lets see the form to add a member.
<form class="form-inline text-center" ng-submit="addMember()">
<div class="form-group">
  <input type="text" class="form-control input-lg" id="txtMember" required="" placeholder="Enter Member Name"
  ng-model="newMember" pattern="[a-zA-Z]+" />
<button type="submit" class="btn btn-primary btn-lg">Add member</button>
The input textbox is binded to the newMember property on the scope of FilterCtrl controller using ng-model directive. It is a two way binding. Basically, ng-model directive binds an input,select, textarea (or custom form control) to a property on the scope. The pattern is an HTML5 attribute, which specifies a regular expression that the <input> element's value is checked against. In this case the input can only contain alphabets. On submitting this form, addMember behaviour on the scope of FilterCtrl controller is triggered. This is achieved using ng-submit directive. This happens only if the form does not contain action, data-action, or x-action attributes. As you can clearly understand from the addMember method, it adds an item to the members array on the scope. Now let us analyse the table used to display the members.
<table class="table table-striped">
 <tr ng-repeat="member in members">
   <td><button class="btn btn-default" ng-click="deleteMember(member)"><span class="glyphicon glyphicon-trash"></span></button></td>
The first thing you’ll notice in this template is the use of expressions (“{{“ and “}}”) to return variable values. In AngularJS, expressions allow you to execute some computation in order to return a desired value. Some valid expressions would be:
  • {{ 1 + 4 }}
  • {{ username }}
The next thing you’ll notice is the use of ng-repeat and ng-click directives. The ng-repeat directive is one of the most commonly used and serves to define your template scope when looping through collections. In the example above, it replicates a line in the table for each member in members. The ng-click directive binds an expression to onclick events. Here it call the deleteMember function on scope of the FilterCtrl controller.

Filtering the members

Adding extra functionality is always fun. So lets add a filtering functionality to our app. This will help us to filter the members list based on a text we feed. For this replace the below line
///For filtering view///
with the below line of codes
<table class="table table-striped">
 <td><input type="text" class="form-control" ng-model="filterTxt" placeholder="Enter filter text"/></td>
  <tr ng-repeat="member in members | filter : filterTxt">
AngularJS filters are used for this purpose. In this code, the data that a user types into the input box (named filterTxt) is immediately available as a filter input in the list repeater (member in members | filter:filterTxt). When changes to the data model cause the repeater's input to change, the repeater efficiently updates the DOM to reflect the current state of the model. So your first angularjs application is ready to test. Always use modern browsers. Hope you enjoy this tutorial. :)