5 Minutes Head-start on How to use AngularJs for web Design ~ Coding Savvy
Coding Savvy FB Twitter Google
» »

5 Minutes Head-start on How to use AngularJs for web Design

Many Web Developers love Jquery but want to try AngularJs because it tempting due to it capabilities, Many are confused on which one to choose between AngularJS and JQuery for their latest project. Before any reccomendation let see what they are made of. JQuery is the most popular JavaScript Library on the web, I has been our favorite all these years and it has make web development easier and faster for us but AngularJs is now gaining our attention because of it productive, flexible, maintainable and testable ability than JQuery, Note that AngularJS is powered by Google Inc. though I personally love Google products (don't ask me why, I just love security) but that dose not justify the reason why I would prefer AngularJS to JQuery because you can't choose one for another in a big project it either you use the combination of both or JQuery alone, In fact AngularJs has a mini in-built JQuery library of it's own. But before we start let get one thing straight whatever JQuery can do AngularJS can do it better, faster and with less coding. Also AngularJS is more powerful when it comes to stand-alone applications. If you are seeking my opinion on which is the most prefered, you already have your answer because JQuery will always tell AngularJs that "Angular, I am your father". Now let get started with introduction to AngularJs.
5 Minutes headstart on How to use AngularJs for web Design
Download Source Codes
AngularJS is a part of this new generation of libraries and frameworks that came to support the development of more productive, flexible, maintainable, and testable web applications.

History of AngularJS

Created by Miško Hevery and Adam Abrons in 2009, AngularJS is an open source, client-side JavaScript framework that promotes a high-productivity web development experience. It was built on the belief that declarative programming is the best choice to construct the user interface, while imperative programming is much better and preferred to implement an application's business logic. To achieve this, AngularJS empowers traditional HTML by extending its current vocabulary, making the life of developers easier. The result is the development of expressive, reusable, and maintainable application components, leaving behind a lot of unnecessary code and keeping the team focused on the valuable and important things. In 2010, Miško Hevery was working at Google on a project called Feedback. Based on Google Web Toolkit (GWT), the Feedback project was reaching more than 17.000 lines of code and the team was not satisfied with their productivity. Because of that, Miško made a bet with his manager that he could rewrite the project in 2 weeks using his framework. After 3 weeks and only 1.500 lines of code, he delivered the project! Nowadays, the framework is used by more than 100 projects just at Google, and it is maintained by its own internal team, in which Miško takes part. The name of the framework was given by Adam Abrons, and it was inspired by the angle brackets of the HTML elements.

Setting up AngularJS

Just like other JavaScript libraries we need to setup AngularJs before use.

Importing AngularJS


Importing the framework into our HTML file is the first step to take during setup.we can import the framework using the script tag. Create the Application Module
We can create the application module by calling the module function from the Angular's API, with its name and dependencies. Initializing AngularJS
To initialize AngularJS we just need to place the ng-app attribute with the module's name inside the html element or any other element that surrounds the application.

Using AngularJS

We have already setup the framework and it has been initialized what we need next is to take it for a spin.
Note:You can download AngularJS from https://angularjs.org
<html ng-app="user">

<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Intro to AngularJS - Codingsavvy.com</title>
<script src="./lib/angularjs.js"></script>
</head>
<body>
</body>
<html>

We have just imported the AngularJS library and initialized it. Let get our hands dirty by creating a mini login Application with AngularJs.

Create Login Application with AngularJs

We are going to create a new AngularJs Module and name it user

<html ng-app="user">

<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Intro to AngularJS - Codingsavvy.com</title>
<script src="./lib/angularjs.js"></script>
<script>
// Creating the module called user
var user = angular.module("user", []);
</script>
</head>
<body>

</body>
<html>

Next we need to create a controller for our application and register it with AngularJs.

Creating AngularJs Controller

Let start by creating a controller for our login application and register it with AngularJs. loginCtrl.js
user.controller("loginCtrl", function ($scope) {

});

Before we go further I will like us to get to know about AngularJs Directives and How to use them .

Using AngularJs Directives

A directive is an extension of the HTML vocabulary that allows us to create new behaviors. This technology lets the developers create reusable components that can be used within the whole application and even provide their own custom components. The directive can be applied as an attribute, element, class, and even as a comment, using the camel Case syntax. However, because HTML is case insensitive, we can use a lowercase form. For the ngModel directive, we can use ng-model, ng:model, ng_model, data-ng-model, and x-ng-model in the HTML markup.

Binding AngularJs Controller to the View

To use AngularJs Controller with our view we need to bind it to an element in our HTML file. In our case let bind it with the body tag we are going to achieve this by using the ng-controller directive which is an AngularJs in-built directive. Note: We can also create our own directives and we are also going to cover it in this tutorial.
<body ng-controller="loginCtrl">

index.html
<!DOCTYPE html> <html ng-app="user" > <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <title>Intro to AngularJS - Codingsavvy.com</title> <script src="./lib/angularjs.js"></script> <script src="./loginCtrl.js"></script> <script> // Creating the module called user var user = angular.module("user", []); </script> </head> <body ng-controller="loginCtrl"> <form> <table> <tr><td>Username : </td> <th><input type="text" name="username" /></th></tr> <tr><td>Password : </td> <th><input type="password" name="password" /></th></tr> <tr><td></td> <th><input type="submit" name="login" value="Login" /></th></tr> </table> </form> </body> <html>

Next we proceed to creating the login function that will be triggered by the login button.

How to create function in AngularJs

To create our login function we create the function and save it in our $scope parameter.
loginCtrl.js
user.controller("loginCtrl", function ($scope) {

$scope.login = function(user){

};

});

We are going to begin the login function to the login button with the ng-click
index.html
<!DOCTYPE html>
<html ng-app="user">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Intro to AngularJS - Codingsavvy.com</title>
<script src="./lib/angularjs.js"></script>
<script src="./loginCtrl.js"></script>
<script>
// Creating the module called user var user = angular.module("user", []);
</script>
</head>
<body ng-controller="loginCtrl">
<form>
<table>
<tr><td>Username : </td> <th><input type="text" name="username" /></th></tr>
<tr><td>Password : </td> <th><input type="password" name="password" /></th></tr>
<tr><td></td> <th><input type="submit" name="login" ng-click="login(user)" value="Login" /></th></tr>
</table>
</form>
</body>
<html>

Next we need to access the user input to the form with AngularJs.

Using AngularJs Model

The model of angularjs framework is referring to the source of data. In our user login application we need to begin by  the username and password field added to our model using ng-model directive.
<tr>
<td>
Username : </td>
<th>
<input type="text" ng-model="user.username" name="username" />
</th>
</tr>
<tr>
<td>
Password : </td>
<th>
<input type="password" ng-model="user.password"name="password" />
</th>
</tr>
<tr>
<td>
</td>
<th>
<input type="submit" name="login" ng-click="login(user)" value="Login" />
</th>
</tr>

Next we need to validate the inputed data.

Form validation with AngularJs

The beauty of using any javascript library in a login page is to validate the user input data before it gets to the server side validation. Form validate through angularjs saves time and it is very quick and efficient way to get things done with less JS codes.
First we need to give our form a name and remember that all the input fields must have their names too.
<form method="post" name="loginForm">

Validate Form Using AngularJs in-built Directives

The validation process is quite simple and relies on some directives to do the job. The first one that we need to understand is the ngRequired directive.
This directive is usefult if a form field is required before the form will be submitted.
<input type="text" name="username" ng-model="user.username" placeholder="Enter your username" ng-required="true" />

Also to set minimum and maximum length for fields you can use :
ng-minlength="6"
ng-maxlength="10"

we can add a regular expression to validate the format of the username or password field by adding this directive to the fields.
ng-pattern="/[A-Z]{3}[0-9]{3,7}/"

The result can be evaluated through the implicit object $valid. It will be defined based on the directives of each field.
To make sure that the user requesting to login has passed the validation test we can disable the login button and enable it if the user passes the tests.
<input type="submit" name="login" ng-click="login(user)" ng-disabled="carForm.$invalid"value="Login" />

To make sure that the user interacting with our application understands what is going on, we need to repore an error whenever users don't pass the form validation tests.
This will bring us to learn how we can create our own custom directives.

Creating custom directives in AngularJs

To create costume directive we require the creation of something called Directive Definition Object that will be used to configure the directive's behavior
user.directive("error", function () { return { }; });

We want or errors to look something like this.
<div class="error" >
<h3>
Error : Unable to Login</h3>
<p>
Invalid Username/Password combination.</p>
</div>

we can add body to our directive like this.
user.directive("error", function () { return { template:"<div class='error' >
"+ "<h3>
Error : Unable to Login</h3>
"+ "<p>
Invalid Username/Password combination.</p>
"+ "</div>
", replace: true,
restrict: 'E'
};
});

The replace is used to replace the already existing elements in our directive position this is essential if we need to replace the original element. We attached our previous in-built directives by defining it as an attribute of the element. However, when we create a new directive as a reusable component, it doesn't make much sense. In this case, a better approach can restrict the directive to be an element.
Restriction property

Values
Usage
Attribute (default)
A
<div alert></div>
Element name
E
<alert></alert>
Class
C
<div class="alert"<</div>
Comment
M
<!-- directive:alert -->

Now we can place our directive anywhere by just pitting this code.
<error> </error>

Now we need to send error messages into our component to replace the hard coded once.
Prefix

Details
@
This prefix passes the data as a string.
=
This prefix creates a bidirectional relationship between a controller's scope property and a local scope directive property.
&
This prefix binds the parameter with an expression in the context of the parent scope. It is useful if you would like to provide some outside functions to the directive.

Our directive will look like this :
<error> title="errorTitle" description="errorDescription" ng-show="showError" close="closeError()" </error>

Now our final directive will look like this :
user.directive("error", function () { return { template:"<div class='error' >
"+ "<h3 ng-bind='title' >
</h3>
"+ "<p ng-bind='description' >
</p>
"+ "<a href='' ng-click='close()'>Close</a>"+ "</div>
", replace: true,
restrict: 'E',
scope: {
title: '=title',
description: '=description',
close: '&close'
} };
});

Communicating with the backend

Server communication is one of the beauty of AngularJs framework , the request is faster and it is easy to render. Let use php to generate the JSON data.
server.php
<?php $data = array(array('username'=>'damsel16','gender'=>'f','live'=>false), array('username'=>'raj','gender'=>'m','live'=>false), array('username'=>'orex','gender'=>'m','live'=>true), array('username'=>'tipsy','gender'=>'f','live'=>true), array('username'=>'mikiel','gender'=>'m','live'=>false)); echo json_encode(array("users"=> $data));

The ouput Data will look like :
{"users":[{"username":"damsel16","gender":"f","live":false}, {"username":"raj","gender":"m","live":false}, {"username":"orex","gender":"m","live":true}, {"username":"tipsy","gender":"f","live":true}, {"username":"mikiel","gender":"m","live":false}]}

AJAX ( HTTP Request ) in AngularJs

AJAX is one of the key feature of web Application, it shows the true flexibility of a page, and it also make you page respond faster to user requests. to demonstrate how fast and flexible it is to user AJAX with AngularJs, We are going to use PHP as our backend server then we are going to use AngularJs AJAX function to pickup the data. The data will be in JSON format because of easy manipulation. This service could be called by just passing a configuration object, used to set a lot of important information such as the method, the URL of the requested resource, the data to be sent, and many others:
$http({method: "GET", url: "/server.php"});
or
$http({method: "GET", url: "/server.php"})
.success(function (data, status, headers, config, statusText) {
})
.error(function (data, status, headers, config, statusText) {
});

or
To make it easier to use, the following shortcut methods are available for this service. In this case, the configuration object is optional:
$http.get(url, [config]) $http.post(url, data, [config]) $http.put(url, data, [config]) $http.head(url, [config]) $http.delete(url, [config]) $http.jsonp(url, [config])

To receive the data from data.php using AngularJs we need to add one more parameter to our Controller:
user.controller("loginCtrl", function ($scope,$http) {

$scope.closeError = function () {
$scope.showError = false;
}
$scope.login = function(user){

if (user){
$scope.errorTitle = "Error : Unable to Login!";
$scope.errorDescription = "Invalid Username/Password combination.!";
$scope.showError = true;
}

}

var getUsers = function () {
$http.get("/server.php")
.success(function(data, status, headers, config) {
$scope.users = data.users;
})
.error(function(data, status, headers, config) {
switch(status) {
case 401: {
$scope.message = "You must be authenticated!"
break;
}
case 500: {
$scope.message = "Something went wrong!";
break;
}
}
console.log(data, status);
});

};



getUsers();


});

Here are some common error codes in HTTP request.
Error CodeDefinition
200OK
400 Bad Request
401 Unauthorized
403 Forbidden
404 Not Found
500 Internal Server Error

let position the registered users table beside the login form.
<div ng-show="usersLoaded">
<table>
<thead>
<tr>
<th>
</th>
<th>
Username</th>
<th>
Gender</th>
<th>
Live</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="user in users" >
<td>
<input type="checkbox" ngmodel=" car.selected"/>
</td>
<td>
<span ng-bind="user.username">
</span>
</td>
<td>
<span ng-bind="user.gender">
</span>
</td>
<td>
<span ng-bind="user.live">
</span>
</td>
</tr>
</tbody>
</table>
</div>
<div ng-hide="users.length >
0">
There are no registered users. </div>

Here is the fnal loginCtrl.js
user.controller("loginCtrl", function ($scope,$http) {

$scope.closeError = function () {

$scope.showError = false;

}
$scope.login = function(user){
if (user){
$scope.errorTitle = "Error : Unable to Login!";
$scope.errorDescription = "Invalid Username/Password combination.!";
$scope.showError = true;
}
}
$scope.usersLoaded = false;
var getUsers = function () {
$http.get("server.php")
.success(function(data, status, headers, config) {
$scope.users = data.users;
$scope.usersLoaded = true;
$scope.message = "Users Loaded successfully";
})
.error(function(data, status, headers, config) {
switch(status) {
case 401: {
$scope.message = "You must be authenticated!"
break;
}
case 500: {
$scope.message = "Something went wrong!";
break;
}
}
console.log(data, status);
});
};

getUsers();

});

user.directive("error", function () {
return {
template:"
"+
"

"+
"
"+
"Close"+
"
",
replace: true,
restrict: 'E',
scope: {
title: '=title',
description: '=description',
close: '&close'
}
};
});

index.html Final:
<!DOCTYPE html>
<html ng-app="user" >
<!-- initializing AngularJS -->
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>
Intro to AngularJS - Codingsavvy.com</title>
<script src="./lib/angularjs.js">
</script>
<script>
// Creating the module called user var user = angular.module("user", []); </script>
<script src="./loginCtrl.js">
</script>
<style>
body,form,table{ text-align:center !important;} form,table{ position:absolute; left:40%; } table{ top:42%; } </style>
</head>
<body ng-controller="loginCtrl" >
<h2>
Introduction to AngularJs by <a href="http://www.codingsavvy.com">
C.S Group</a>
</h2>
<h3>
Get full tutorial at <a href="http://www.codingsavvy.com">
www.codingsavvy.com</a>
</h3>
<form>
<table>
<tr>
<td>
</td>
<td>
<error ng-show="showError" close="closeError()" title="errorTitle" description="errorDescription" >
</error>
</td>
</tr>
<tr>
<td>
Username : </td>
<th>
<input type="text" ng-required="true" ng-model="user.username" name="username" />
</th>
</tr>
<tr>
<td>
Password : </td>
<th>
<input type="password" ng-required="true" ng-model="user.password" name="password" />
</th>
</tr>
<tr>
<td>
</td>
<th>
<input type="submit" name="login" ng-click="login(user)" value="Login" />
</th>
</tr>
</table>
</form>
<div ng-show="usersLoaded">
<table>
<thead>
<tr>
<th>
</th>
<th>
Username</th>
<th>
Gender</th>
<th>
Live</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="user in users" >
<td>
<input type="checkbox" ngmodel=" car.selected"/>
</td>
<td>
<span ng-bind="user.username">
</span>
</td>
<td>
<span ng-bind="user.gender">
</span>
</td>
<td>
<span ng-bind="user.live">
</span>
</td>
</tr>
</tbody>
</table>
</div>
<div ng-hide="users.length >
0">
There are no registered users. </div>
</body>
<html>

Download Source Codes
Was this article helpful?
Thanks! Your feedback helps us improve tutorials.

You May Also Like...

2 comments:

  1. Great post. I really learned some new things in here. So thanks.

    school branding

    ReplyDelete