AngularJS – the conceptual overview

The following section introduces the important parts of AngularJS:

  • AngularJS is like other libraries in which you can invoke the functions as you want.
  • Everything is designed to be used as a collaborative suite.
  • The applications designed using AngularJS need two things to start:
    • You need to load the angular.js library.
    • You need to tell AngularJS which part of the DOM it should manage with ng-app directive. AngularJS can be loaded from Google's content delivery network (CDN).

The following code shows how to load AngularJS using CDN:

<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.4/angular.min.js"></script>
</head>

It is recommended that you use Google's CDN, as shown in the preceding code, because Google's servers are fast and the script is cacheable across applications. If you prefer to host locally, you can do that too. Just specify the correct location in src, as shown in the following code:

<head>
<script src="~/scripts/angular.min.js"></script>
</head>

It is not required that you use AngularJS on the whole page, it can also be used only for a specific part of the page. The ng-app directive lets AngularJS know which part of the HTML (DOM) should be managed. If the whole application is developed by using AngularJS, then include ng-app in the <html> tag, as shown in the following code:

<htmlng-app>
<head>
<script src="~/scripts/angular.min.js"></script>
</head>
<body>

</body>
</html>

If the application is developed where some other technology supposes to manage the application along with AngularJS, then add the ng-app directive to where the application HTML (DOM) will be managed by AngularJS:

<html>
<head>
<script src="~/scripts/angular.min.js"></script>
</head>
<body>
<divng-app>
…
</div>
</body>
</html>

Templates

Templates in AngularJS are HTML files with extra markup. This markup consists of directives that show how the model ought to be represented in the view. AngularJS manipulates the DOM and not strings (in distinction to alternative JavaScript frameworks).

Directives

In AngularJS, the sole place where an application touches the DOM is within its directives. Directives permit extending markup language; they'll be used to produce custom HTML tags or to decorate existing ones with new behavior.

Let's create a directive that adds copyright information by using a new <copyright> tag:

var app = angular.module('app', []);
app.directive('copyright', function(){
return {
restrict: "E",
replace: true,
template: "<p>Copyright 2014</p>"
}
});

In the preceding code snippet, we created a directive, copyright. Directives have different types. Templates specify the HTML content that should be displayed when it's executed. By default, directives are restricted to attributes. However, to trigger them according to attributes, class, or name, we can use the restrict directive as follows:

  • restrict: 'E': This means we should use an HTML tag to reference it, that is <copyright>
  • restrict: 'A': This is for attribute that is <div copyright>
  • restrict: 'C': This is for class that is <div class="copyright">

The following code uses the HTML tag to reference the directive:

<body ng-app="app" >

<copyright>
</copyright>

</body>

Filters

An AngularJS filter is accustomed to remodel data. A filter is added to expressions and directives that employ a pipe character. You would also use filters in controllers, services, and directives. You can also create your own filters, which will be discussed in detail in Chapter 3, AngularJS Scopes, Controllers, and Filters, as shown:

<input ng-model="value" type="text" placeholder="Try to enter a number    
with 3 or more decimal places...">
<h1>{{value | number:2}}</h1>

The filter used in the expression here, {{value | number:2}}, will only display a value of up to two decimal places. To implement a filter, the pipe symbol | is used after the variable, value.

Services

Services are meant to share data between controllers. In other words, they supply a centralized purpose of giving access to the data. The aim of an AngularJS service is to come up with one object or function that represents the service to the remainder of the application.

In the following code example, a service is shared between two controllers. In this way, each controller will access and manipulate the data that was entered within the input managed by the other controller:

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

app.service('MessageService', function () {
this.payload = { message: 'Hello from a Service' };
});

app.controller('FirstController', function ($scope, MessageService) {
    $scope.payload = MessageService.payload;
});

app.controller('SecondController', function ($scope, MessageService) {
    $scope.payload = MessageService.payload;
});

It will be rendered in HTML, as follows:

<body ng-app="app">
<div ng-controller="FirstController>
<input type="text" ng-model="payload.message"/>
</div>

<div ng-controller="SecondController">
<input type="text" ng-model="payload.message"/>
</div>
</body>

In the preceding code and following diagram, the application contains two controllers, FirstController and SecondController. Each of these controllers requires certain user data. Thus, instead of repeating the logic to fetch data in each controller, we will create a user service, which will hide the complexity. AngularJS automatically injects the user service in both, FirstController and SecondController. Therefore, our application becomes modular and testable. The following figure depicts the user services:

Services

The following are some examples of a few services of AngularJS Framework:

Service

Description

$http

This allows access to HTTP requests

$resource

This provides a higher-level abstraction to access REST-style services

$document

This is a jQuery wrapped reference to window.document

$window

This is a jQuery wrapped reference to window

$timeout

This is a wrapped version of window.setTimeout

$parse

This parses AngularJS expressions (for example, for binding with ng-model or similar expressions) and provides accessor functions

$cacheFactory

This is usually used by other services whenever they need a scoped cache of elements

$filter

This provides programmatic access to a filter function

Dependency Injection

Dependency Injection is a software system pattern, which means that if an object needs another object (a dependency), this dependency will be passed to that object rather than it being made (for example, initialized) by that object. Imagine it in the following manner: you define what objects you wish for and they are able to work for you right away. It makes the application easier to develop, as shown in the following code:

functionUserController($scope) {

   $scope.currentUser = {
firstName: 'John',
lastName: 'Doe'
   };

}

In the preceding code snippet, $scope gets injected by AngularJS whenever this controller is instantiated.

The compiler

After AngularJS finds the ng-app directive, it'll create a new $rootScope and then compile the child DOM components of the root node. To compile an HTML (DOM) element, we are compelled to use the $compile service. However, AngularJS has the capability to handle it, and $compile takes a markup or jQuery object and returns a linking function that is then known as the scope for it to bind to. Once the linking function is called, it returns an angular component that has the practicality of a jQuery object. However, it conjointly contains a scope and numerous different angular-specific data. Before, or once the compilation is complete, the following components are often inserted in the page:

  • Compile: This component traverse the DOM and collect all the directives.
  • Link: This component mix the directives with a scope and turn out a live view. Any changes within the scope model are reflected within the view, and any user interactions with the view are mirrored within the scope model. This makes the scope model the single supply of truth.

Some directives such as ng-repeat clones DOM components once for every item in a very assortment. Having a compile and link part improves performance since the cloned guide solely has to be compiled once and then linked once for every clone instance.

The $compile perform traverses the DOM and appears for the directives. For every directive it finds, it adds that directive to a list of directives. Once the complete DOM is traversed, it will arrange that list of directives according to their priority. Then, every directive's own compile perform is dead, which gives every directive the possibility to change the DOM itself. Every compile perform returns a linking perform, which is then composed into a "combined" linking function and is returned. AngularJS executes the linking performance and ensures to pass it within the scope that we wish to bind it to within this method. This can run all the linking functions that bind the same scope or bet on the directive to produce new scopes. Once all the linking functions are dead, the combined linking perform returns a collection of DOM elements complete with data-bindings and event listeners that AngularJS can append to the parent node.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset