The Basic Elements of AngularJS

1
338
Angular

Angular JS

Here is an introductory article to AngularJS, a very powerful JavaScript framework. It can be added to an HTML page with a <script> tag. Read on to know and understand more about its features.

AngularJS is a JavaScript framework that allows you to extend HTML into a more readable and presentable format. It enables you to write your application logic instead of manually updating views. AngularJS helps to write cleaner and more efficient code for creating rich and interactive single page applications (SPAs).
The general features of AngularJS are shown in Figure 1.

Figure 1
Figure 1: Main features of Angular JS

Why AngularJS?
A single page application is one that has a shell page and contains multiple views in the page. The challenge with building single page applications from scratch is that there are a lot of different issues to deal with, as shown in Figure 2.

Figure 2
Figure 2: Challenges with SPAs

AngularJS provides solutions to all these challenges. It is a full-featured SPA framework. Some of the core features are described in Figure 3.

Figure 3
Figure 3: Core features of AngularJS

A ‘Hello World’ example
First, all we have to do is include Angular JS JavaScript in our HTML document, as follows:

<!doctype html>
<html ng-app>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js"></script>
</head>
<body>
<div>
<label>Name:</label>
<input type="text" ng-model="yourName" placeholder="Enter a name here">
<hr>
<h1>Hello {{yourName}}!</h1>
</div>
</body>
</html>

ng-app: This attribute stands for the active portion of the entire page. As per our code, it is the whole document. If you want to activate some specific location, then apply the ng-app attribute to that specific location tag.
ng-model and two-way data binding: ng-model binds the model value with the state of the text box. As per our code, we have defined a model as yourname. This value is attached with the value of the textbox using the ng-model attribute. So the change in the text box value will automatically reflect in the model yourname. This is nothing but two-way data binding. Similarly, if the model value is changed, then Angular will change the value of the text box.
The output of the ‘Hello World’ example is given in Figure 4.

Figure 4
Figure 4: Output of ‘Hello World’

Basic directives
Directives are nothing but the markers on a DOM element, which tell the compiler to attach a specified event or behaviour to that element.
Angular comes with a set of built-in directives. Some of these are described below.

  • ng-app: Initiates an AngularJS application
  • ng-init: Initialises application data
  • ng-model: Defines the model to be used in AngularJS
  • ng-repeat: Repeats HTML elements for each item in a collection
  • ng-bind: Binds the data to the element and is an alternative to the interpolation directive
  • ng-show: Shows the HTML element
  • ng-hide: Hides the model element
  • ng-switch: Used to add or remove elements from DOM, based on data
  • ng-if: Same as switch, just has a simpler syntax
  • ng-include: Includes the HTML elements from other files

MVC architecture
Model View Controller (MVC) is a software design pattern used for the development of Web applications. It is made up of the following three parts:

  • Model – the lowest level, which is responsible for maintaining data.
  • View – responsible for displaying all or a portion of the data to the user.
  • Controller – controls the interactions between the Model and View.

Model
The model contains the data to be displayed, as well as data to be collected in any input fields or forms. Additionally, it may contain functions that are called based on user input or other activities. A model in Angular is just a plain JavaScript object. It can be a primitive type such as a string, number, Boolean or a complex type such as an object.

View
View is nothing but how you present the data in a particular format. It may be triggered by the controller’s decision. The view in an AngularJS application is created using HTML. View is what users see. It binds data from the model inside your controller, and will get updated automatically if there are model changes from the controller, since Angular has two-way data binding. There is no need to write additional code to achieve this.

Controller
Controller is the place where the application logic resides. It is simply formed by JavaScript classes. In it, we can also call other components to work with. The controller is where the model lives.
The controller for a view is used to pull together the model used by the view and handle the input from the consumer of the view. In AngularJS, the controller is resolved by name, from the ng-controller directive.

<html ng-app=”testApp”>  
<head>  
<title>MVC Architecture code</title>  
<script SRC=”https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.js”>  
</script>  
<script type=”text/javascript”>  
//Creating controller here  
var app = angular.module('testApp', []);  
    app.controller('callcontroller', function($scope) {  
    //Creating model here  
    $scope.employee =  {  
         'Name'    :   'ABC',  
         'Address' :   '12-13-283/A1',  
         'Email'   :   'abc@xyz.com'  
     }  
    });  
</script>  
</head>  
<body>  
<p>Displaying model data in view through controller</p>  
<div ng-controller="callcontroller">  
<h3>{{ employee .Name }} </h3>  
<h3>{{ employee .Address }} </h3>  
<h3>{{ employee .Email }} </h3>  
</div>  
</body>  
</html>

The output displays the model data in view, through the controller:

ABC
12-13-283/A1
abc@xyz.com

Filters
Filters are used to modify the data and can be used in expressions or directives, using the pipe character. The following is a list of commonly used filters.

Name  Description
uppercase Converts text to upper case.
lowercase  Converts text to lower case.
 currency  Converts text to a currency format.
 filter  Filters the array to a subset of it, based on the provided criteria.
 orderby  Orders the array based on the provided criteria.

Building your own directives
AngularJS allows you to build your own custom directives, which are nothing but an extension to the HTML. They are defined using the ‘directive’ function, and simply replace the element for which they are activated. AngularJS finds the matching elements and processes them once, using its compile() method; it then processes the elements using the link() method of the custom directive based on the scope. It supports the creation of custom directives for the following types of elements.

  • Element directives: It activates once a matching element is encountered.
  • Attribute: It activates once a matching attribute is encountered.
  • CSS: It activates once a matching CSS style is encountered.
  • Comment: It activates once a matching comment is encountered.

Given below is the sample program that shows the construction of custom directives.

<html>
<head>
<title> Building Your Own Directives</title>
</head>
<body>
<h2>AngularJS Test Application</h2>
<div ng-app = “mainApp” ng-controller = “testEmployeeController”>
<Employee name = “ABC”></Employee><br/>
<Employee name = “XYZ”></Employee>
</div>
<script src = “http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js”></script>
<script>
var mainApp = angular.module(“mainApp”, []);
mainApp.directive(‘Employee’, function() {
var directive = {};
directive.restrict = ‘E’;
directive.template = “Employee: <b>{{Employee.name}}</b> , ID: <b>{{Employee.id}}</b>”;
directive.scope = {
Employee : “=name” }
directive.compile = function(element, attributes) {
element.css(“border”, “1px solid #cccccc”);
var testFunction = function($scope, element, attributes) {
element.html(“Employee: <b>”+$scope.Employee.name +”</b> , ID: <b>”+ $scope.Employee.id + “</b><br/>”);
element.css(“background-color”, “#00FFFF “);
}
return linkFunction;
}
return directive;
});
mainApp.controller(‘TestEmployeeController’, function($scope) {
$scope.ABC = {};
$scope.ABC.name = “ABC”;
$scope.ABC.id = 1;
$scope.XYZ = {};
$scope.XYZ.name = “XYZ”;
$scope.XYZ.id = 2;
});
</script>
</body>
</html>

The output is the AngularJS test application:

Employee: ABC, ID: 1
Employee: XYZ, ID: 2
Figure 5
Figure 5: MVC architecture

Dependency injection
AngularJS contains a built-in dependency injection mechanism. This is the key to making easily reusable and testable components. It is a software pattern that ensures references to other components are not created directly for the components. Instead of direct instantiation, each component will get references required by other components. So there is no need to find the dependencies for components, as dependencies themselves are configurable. The application will be divided into different components, which can be injected into each other. This makes your application easily reusable, configurable and testable.
AngularJS contains the following core types of objects and components:

  • Value
  • Factory
  • Service
  • Provider
  • Constant

Value
Value is a simple object and used to inject values to the controller, factories or services during the configuration phase. It can be a number, string or JavaScript object. A value must belong to an AngularJS module.
Here are some examples that add values to an AngularJS module:

var myModule = angular.module(“testModule”, []);
testModule.value(“numberValue”, 100);
testModule.value(“stringValue”, “ABC”);
testModule.value(“objectValue”, { val1 : 100, val2 : “XYZ”} );

The values are defined using the value() function on the module. The first parameter is the name of the value, and the second parameter is the value itself. Factories, services and controllers can now refer to these values by their name.

Factory
Factory is a function that is used to create value. It creates value whenever a service or controller needs it. The factory function is used to calculate and return the value. Once it is created, the value is reusable for all services, controllers, etc.
Here is an example that defines a factory on a module, and a controller which gets the factory-created value injected:

var testModule = angular.module(“testModule”, []);
testModule.factory(“testFactory”, function() { return “abc”;});
testModule.controller(“MyController”, function($scope, testFactory) {
console.log(testFactory);
});

Service
A service is a singleton JavaScript object, which is a set of functions to achieve specific tasks. The functions contain the necessary logic for the service to carry out its tasks. They are defined using service() functions and then used in controllers.

TestModule.service(“testService”.MyService)

MyService is nothing but a function.

Providers
Providers in AngularJS are the most flexible, and are used to create services, factories, etc. You can register a provider with a module just like you handle a service or factory, except that you must use the provider() function instead.

Constants
Constants are used to pass values during the config phase by taking into consideration the fact that the value cannot be passed during this phase. Constants in AngularJS are defined using the module.constants() function. Shown below is an example of an AngularJS constant:

testModule.constant(“configValue”.”constant config value”)

1 COMMENT

  1. […] the first glimpse of Mavo makes an option similar to AngularJS, there are some differences that make both the distinguished […]

LEAVE A REPLY

Please enter your comment!
Please enter your name here