Ontoborn.com

@Ontoborn99

Angularjs — Learning [For Beginners]

AngularJS is a very powerful JavaScript Framework. It is used in Single Page Application (SPA) projects. It also extends HTML DOM with additional attributes and makes it more responsive to user actions. AngularJS is open source, completely free, and used by thousands of developers around the world. It is licensed under the Apache license version 2.0

AngularJS changes static HTML to dynamic HTML. It also extends the ability of HTML by adding built-in attributes and components and also provides an ability to create custom attributes using simple JavaScript

AngularJS Example:

The following is a simple AngularJS example that changes a label to whatever you type in the textbox.

Result

Advantages of AngularJS:

  1. Open source JavaScript MVC framework.
  2. Supported by Google
  3. No need to learn another scripting language. It’s just pure JavaScript and HTML.
  4. Supports separation of concerns by using MVC design pattern.
  5. Built-in attributes (directives) makes HTML dynamic.
  6. Easy to extend and customize.
  7. Supports Single Page Application.
  8. Uses Dependency Injection.
  9. Easy to Unit test.
  10. REST friendly.

First AngularJS Application:

Let’s create a simple AngularJS web application step by step and understand the basic building blocks of AngularJS.

  1. First, create an HTML document with <head> and <body> elements, as show below.

Example: HTML Template

<!DOCTYPE html>

<html>

<head> </head>

<body> </body>

</html>

  1. Include angular.js file in the head section

Example: Include AngularJS Library

<!DOCTYPE html>

<html>

<head>

<title>First AngularJS Application</title>

<script src= “~/Scripts/angular.js”></script>

</head>

<body> </body>

</html>

  1. Here, we will be creating a simple addition application which will add two numbers and display the result. User will enter two numbers in two separate textboxes and the result will be displayed immediately, as shown below.

First AngularJS Application

The following is the HTML code with AngularJS for the above Addition example.

Example:

First AngularJS Application

<!DOCTYPE html>

<html>

<head>

<title>First AngularJS Application</title>

<script src= “~/Scripts/angular.js”></script>

</head>

<body ng-app >

<h1>First AngularJS Application</h1>

Enter Numbers to ADD: <input type=”text” ng-model=“Num1” /> + <input type=”text” ng-model=“Num2” /> = <span>{{Num1 + Num2}}</span>

</body>

</html>

The above example is looks like HTML code with some strange attributes and braces such as ng-app, ng-model, and {{ }}. These built-in attributes in AngularJS are called directives.

Template:

In AngularJS, a template is HTML with additional markups. AngularJS compiles templates and renders the resultant HTML.

Directive:

Directives are markers (attributes) on a DOM element that tell AngularJS to attach a specific behavior to that DOM element or even transform the DOM element and also its children.

Most of the directives in AngularJS are starting with ng. It stands for Angular. We have applied ng-app and ng-model directive in the above example.

ng-app: The ng-app directive is a starting point. If AngularJS framework finds ng-app directive anywhere in the HTML document then it bootstraps (initializes) itself and also compiles the HTML template.

ng-model: The ng-model directive binds HTML element to a property on the $scope object. You will learn about this model later but for now let us consider this as a model property.

In the above example, we have included ng-model directive to both the text boxes with different names Num1 and Num2. AngularJS framework will create two properties called Num1 and Num2 in the scope and will also assign a value that we type into text boxes.

Expression:

An expression is like JavaScript code which is usually wrapped inside double curly braces such as {{ expression }}. AngularJS framework evaluates the expression and produces a result. In the above example, {{ Num1 + Num2}} will simply display the sum of Num1 and Num2.

The following table lists all the important concepts in AngularJS.

ConceptDescriptionTemplateHTML with additional markupDirectivesExtends the HTML with custom attributes and elementsModelThe data shown to the user in the view and with which the user interactsScopeA context where the model is stored so that controllers, directives and expressions can also access itExpressionsExecutes JavaScript code inside brackets {{ }}.CompilerParses the template and instantiates directives and expressionsFilterFormats the value of an expression for display to the userViewwhat the user sees (the DOM)Data BindingSync data between the model and the viewControllerMaintains the application data and business logicModulea container for different parts of an app including controllers, services, filters, directives which configure the InjectorServiceReusable business logic, independent of viewsDependency InjectionCreates and wires objects and functionsInjectorDependency injection container

Learn about the ng-app directive in the next section.

The ng-app Directive:

The ng-app directive is a starting point of AngularJS Application. It initializes the AngularJS framework automatically. AngularJS framework will first check for ng-app directive in a HTML document after the entire document is loaded and if ng-app is found, it bootstraps itself and also compiles the HTML template.

Typically ng-app directives should be placed at the root of an HTML document e.g. <html> or <body> tag, so that it can control the entire DOM hierarchy. However, you can also place it in any DOM element.The AngularJS framework will only process the DOM elements and its child elements where the ng-app directive is applied. Consider the following example.

Result

In the above example, ng-app directive is placed in the div element whose id is “ontoborn”. Therefore, AngularJS will only compile myDiv and its child elements. It will not compile the parent or sibling elements of myDiv.

ng-app with Module name:

The ng-app directive can also specify an application module name. This application module also separates different parts of your application such as controllers, services, filters etc.

Result

In the above example, we have specified a module name using ng-app = ‘myAngularApp’ in the <body> tag, and then we have created ‘myAngularApp’ module using angular.module() function inside <script>.

AngularJS Expression:

Angular expression is like JavaScript expression surrounded with braces — {{ expression }}. AngularJS evaluates the specified expression and also binds the result data to HTML.

Expression can contain literals, operators and also variables like JavaScript expression. For example, an expression {{8/2}} will produce the result 4 and will be bound to HTML.

Result

AngularJS Directives:

Directives are markers on a DOM element that tell AngularJS to attach a specified behavior to that DOM element or even transform the DOM element and also its children. In short, it extends the HTML.

Most of the directives in AngularJS are starting with ng- where ng stands for Angular. AngularJS also includes various built-in directives. In addition to this, you can also create custom directives for your application.

The following table lists the important built-in AngularJS directives.

ng-app:

The ng-app directive initializes AngularJS and also makes the specified element a root element of the application.

ng-init:

The ng-init directive can be used to initialize variables in AngularJS application.

The following example demonstrates ng-init directive that initializes variable of string.

Result

In the above example, we initialized variables of string, number, array and object. These variables can also be used anywhere in the DOM element hierarchy where it is declared.

ng-model:

The ng-model directive is used for two-way databinding in AngularJS. It also binds <input>, <select> or <textarea> elements to a specified property on the $scope object. So, the value of the element will be the value of a property and vica-versa.

Result

The property set via ng-model can be accessed in a controller using $scope object

ng-bind:

The ng-bind directive binds the model property declared via $scope or ng-model directive or the result of an expression to the HTML element. It also updates an element if the value of an expression changes.

Result

In the above example, ng-bind directive binds a result of an expression “5 + 5” to the <span>. The same way, it binds a value of a model property “name” to the <span>. The value of “name” property will also be the value entered in a textbox.

ng-repeat:

The ng-repeat directive repeats HTML once per each item in the specified array collection

Result

In the above example, ng-repeat is used with students array. It creates <li> element for each item in the students array. Using the same way it repeats the <div> element.

AngularJS Controller:

The controller in AngularJS is a JavaScript function that maintains the application data and behavior using $scope object.

You can also attach properties and methods to the $scope object inside a controller function, which in turn will add/update the data and attach behaviors to HTML elements. The $scope object is a glue between the controller and HTML.

The ng-controller directive is also used to specify a controller in HTML element, which will add behavior or maintain the data in that HTML element and its child elements.

The following example demonstrates attaching properties to the $scope object inside a controller and then displaying property value in HTML.

Result

In the above example, ng-controller=”myController” directive is applied to the <div> element where “myController” is the name of the controller. Inside div element, we have specified {{message}} expression.

Scope in AngularJS:

The $scope in an AngularJS is a built-in object, which also contains application data and methods. You can create properties to a $scope object inside a controller function and assign a value or function to it.

The $scope is glue between a controller and view (HTML). It transfers data from the controller to view and vice-versa.

Result

AngularJS creates and injects a different $scope object to each controller in an application. So, the data and methods attached to $scope inside one controller cannot be accessed in another controller. With the nested controller, child controller will inherit the parent controller’s scope object. Therefore, child controller can also access properties added in parent controller but parent controller cannot access properties added in child controller.

The ng-model directive is used for two-way data binding. It transfers the data from controller to view and vice-versa. An expression and ng-bind directive also transfers data from controller to view but not vice-versa.

$rootScope:

An AngularJS application has a single $rootScope. All the other $scope objects are child objects.

The properties and methods attached to $rootScope will be available to all the controllers.

Following example demonstrates the $rootScope and $scope object.

Result

As per the above example, properties added in $rootScope are available in all the controllers.

AngularJS Events:

AngularJS also includes certain directives which can be used to provide custom behavior on various DOM events, such as click, dblclick, etc.

ng-click:

The ng-click directive is used to provide event handler for click event.

Result

In the above example, ng-click directive is used to call a DisplayMessage() function with the ‘password’ parameter when a user clicks a button. A ‘password’ is a model property defined using ng-model directive in the input box. The DisplayMessage() function is attached to a $scope object in myController, so it will be also accessible from button click as button comes under myController. The $window service is used to display an alert.

References

Tutorials Teacher

Hire AngularJS Developers

You can hire Angularjs developers at an hourly, weekly or monthly basis at http://ontoborn.com

More by Ontoborn.com

Topics of interest

More Related Stories