Introducing AngularJS

2
5300

Angular-JS-Visual

AngularJS is an open source Web application framework maintained by Google and the community, which helps to build Single Page Applications (SPA). Let’s get to know it better.

AngularJS can be introduced as “a front-end framework capable of incorporating the dynamicity of JavaScript with HTML.” The self-proclaimed ‘super heroic’ JavaScript MVW (Model View Whatever) framework is maintained by Google and many other developers at Github. This open source framework works its magic on Web applications of the Single Page Applications (SPA) category. The logic behind an SPA is that an initial page is loaded at the start of an application from the server. When an action is performed, the application fetches the required resources from the server and adds them to the initial page. The key point here is that an SPA just makes one server round trip, providing you with the initial page. This makes your applications very responsive.

Figure-1
Figure 1 : Report from google trends

Why AngularJS?
AngularJS brings out the beauty in Web development. It is extremely simple to understand and code. If you’re familiar with HTML and JavaScript, you can write the ‘Hello World’ program in minutes. With the help of Angular, the combined power of HTML and JavaScript can be put to maximum use. One of the prominent features of Angular is that it is extremely easy to test. And that makes it very suitable for creating large-scale applications. Also, the Angular community, comprising Google’s developers primarily, is very active in the development process. Google Trends gives assuring proof of Angular’s future in the field of Web development (Figure 1).
Core features
Before getting into the basics of AngularJS, you need to understand two key terms--—templates and models. The HTML page that is rendered out to you is pretty much the template. So basically, your template has HTML, Angular entities (directives, filters, model variables, etc) and CSS (if necessary). The example code given below for data binding is a template.

In an SPA, the data and presentation of data is separated by a model layer that handles data and a view layer that reads from models. This helps an SPA in redrawing any part of the UI without requiring a server round trip to retrieve HTML. When the data is updated, its view is notified and the altered data is produced in the view.

Data binding
AngularJS provides you with two-way binding between the model variables and HTML elements. One-way binding would mean a one-way relation between the two—when the model variables are updated, so are the values in the HTML elements; but not the other way around. Let’s understand two-way binding by looking at an example:

<html ng-app >
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js">
</script>
</head>
<body ng-init = “yourtext = ‘Data binding is cool!’ ”>
Enter your text: <input type="text" ng-model = "yourtext" />
<strong>You entered :</strong> {{yourtext}}
</body>
</html>

The model variable yourtext is bound to the HTML input element. Whenever you change the value in the input box, yourtext gets updated. Also, the value of the HTML input box is initialised to that of the yourtext variable.

Directives
In the above example, many words like ng-app, ng-init and ng-model may have struck you as odd. Well, these are attributes that represent directives – ngApp, ngInit and ngModel, respectively. As described in the official AngularJS developer guide, “Directives are markers on a DOM element (such as an attribute, element name, comment or CSS class) that tell AngularJS’s HTML compiler ($compile) to attach a specified behaviour to that DOM element.” Let’s look into the purpose of some common directives.

ngApp:This directive bootstraps your angular application and considers the HTML element in which the attribute is specified to be the root element of Angular. In the above example, the entire HTML page becomes an angular application, since the ‘ng-app’ attribute is given to the <html> tag. If it was given to the <body> tag, the body alone becomes the root element. Or you could create your own Angular module and let that be the root of your application. An AngularJS module might consist of controllers, services, directives, etc. To create a new module, use the following commands:

var moduleName = angular.module( ‘moduleName ‘, [ ] );
// The array is a list of modules our module depends on

Also, remember to initialise your ng-app attribute to moduleName. For instance,

<html ng-app = “moduleName” >

ngModel: The purpose of this directive is to bind the view with the model. For instance,

<input type = "text" ng-model = "sometext" />
<p> Your text: {{ sometext }}</p>

Here, the model ‘sometext’ is bound (two-way) to the view. The double curly braces will notify Angular to put the value of ‘sometext’ in its place.
ngClick: How this directive functions is similar to that of the onclick event of Javascript.

<button ng-click="mul = mul * 2" ng-init="mul = 1"> Multiply with 2 </button>
After multiplying : {{mul}}

Whenever the button is clicked, ‘mul’ gets multiplied by two.
Filters
A filter helps you in modifying the output to your view. You can subject your expression to any kind of constraints to give out the desired output. The format is:

{{ expression | filter }}

You can filter the output of filter1 again with filter2, using the following format:

{{ expression | filter1 | filter2 }}

The following code filters the members of the people array using the name as the criteria:

<body ng-init=" people=[{name:'Tony',branch:'CSE'},
{name:'Santhosh', branch:'EEE'},
{name:'Manisha', branch:'ECE'}];">
Name: <input type="text" ng-model="name"/>
<li ng-repeat="person in people | filter: name"> {{person.name }} - {{person.branch}}
</li>
</body>

Advanced features
Controllers: To bring some more action to our app, we need controllers. These are JavaScript functions that add behaviour to our app. Let’s make use of the ngController directive to bind the controller to the DOM:

<body ng-controller="ContactController">
<input type="text" ng-model="name"/>
<button ng-click="disp()">Alert !</button>
<script type="text/javascript">
function ContactController($scope) {
$scope.disp = function( ){
alert("Hey " + $scope.name);
};
}
</script>
</body>

One term to be explained here is ‘$scope’. To quote from the developer guide: “Scope is an object that refers to the application model.” With the help of scope, the model variables can be initialised and accessed. In the above example, when the button is clicked the disp( ) comes into play, i.e., the scope is assigned with a behaviour. Inside disp( ), the model variable name is accessed using scope.
Views and routes: In any usual application, we navigate to different pages. In an SPA, instead of pages, we have views. So, you can use views to load different parts of your application. Switching to different views is done through routing. For routing, we make use of the ngRoute and ngView directives:

var miniApp = angular.module( 'miniApp', ['ngRoute'] );

miniApp.config(function( $routeProvider ){
$routeProvider.when( '/home', { templateUrl: 'partials/home.html' } );
$routeProvider.when( '/animal', {templateUrl: 'partials/animals.html' } );
$routeProvider.otherwise( { redirectTo: '/home' } );
});

ngRoute enables routing in applications and $routeProvider is used to configure the routes. home.html and animals.html are examples of ‘partials’; these are files that will be loaded to your view, depending on the URL passed. For example, you could have an app that has icons and whenever the icon is clicked, a link is passed. Depending on the link, the corresponding partial is loaded to the view. This is how you pass links:

<a href='#/home'><img src='partials/home.jpg' /></a>
<a href='#/animal'><img src='partials/animals.jpg' /></a>

Don’t forget to add the ‘ng-view’ attribute to the HTML component of your choice. That component will act as a placeholder for your views.

<div ng-view=""></div>

Services: According to the official documentation of AngularJS, “Angular services are substitutable objects that are wired together using dependency injection (DI). You can use services to organise and share code across your app.” With DI, every component will receive a reference to the service. Angular provides useful services like $http, $window, and $location. In order to use these services in controllers, you can add them as dependencies. As in:

var testapp = angular.module( ‘testapp’, [ ] );
testapp.controller ( ‘testcont’, function( $window ) {
//body of controller
});

To define a custom service, write the following:

testapp.factory ('serviceName', function( ) {
var obj;
return obj; // returned object will be injected to the component
//that has called the service
});

Testing
Testing is done to correct your code on-the-go and avoid ending up with a pile of errors on completing your app’s development. Testing can get complicated when your app grows in size and APIs start to get tangled up, but Angular has got its own defined testing schemes. Usually, two kinds of testing are employed, unit and end-to-end testing (E2E). Unit testing is used to test individual API components, while in E2E testing, the working of a set of components is tested.
The usual components of unit testing are describe( ), beforeEach( ) and it( ). You have to load the angular module before testing and beforeEach( ) does this. Also, this function makes use of the injector method to inject dependencies. The test to be conducted is given in it( ). The test suite is describe( ), and both beforeEach( ) and it( ) come inside it. E2E testing makes use of all the above functions. One other function used is expect( ). This creates ‘expectations’, which verify if the particular application’s state (value of a variable or URL) is the same as the expected values.
Recommended frameworks for unit testing are Jasmine and Karma, and for E2E testing, Protractor is the one to go with.

Who uses AngularJs?
Some of the following corporate giants use AngularJS:

  • Google
  • Sony (YouTube on PS3)
  • Virgin America
  • Nike
  • msnbc (msnbc.com)

You can find a lot of interesting and innovative apps in the ‘Built with AngularJS’ page.

table

The chart above covers only the core features of the three frameworks. Angular is the oldest of the lot and has the biggest community.

References

[1] http://singlepageappbook.com/goal.html
[2] https://github.com/angular/angular.js
[3] https://docs.angularjs.org/guide/
[4] http://karma-runner.github.io/0.12/index.html
[5] http://viralpatel.net/blogs/angularjs-introduction-hello-world-tutorial/
[6] https://builtwith.angularjs.org/

2 COMMENTS

  1. AngularJS is a JavaScript-based open-source and front-end web application structure fundamentally kept up by Google and has a group of people in creating single-page applications. The structure is utilized for creating cross-stage portable applications. Its fundamental points are to rearrange both the improvement and the testing of uses by giving a system to model– view– controller (MVC) and model– view– see demonstrate (MVVM) structures, alongside parts which are utilized as a part of rich Internet applications. take after this URL: https://goo.gl/x525JT to find out about AngularJS.

LEAVE A REPLY

Please enter your comment!
Please enter your name here