Tutorials | Angular js Tutorial

AngularJS Tutorial

AngularJS was developed in 2008-2009 by Misko Hevery and Adam Abrons and is now maintained by Google. AngularJS is a Javascript open-source front-end framework that is mainly used to develop single-page web applications(SPAs). It is a continuously growing and expanding framework which provides better ways for developing web applications.

This AngularJS tutorial is designed for beginners as well as professionals, which covers a wide range of important topics, including AngularJS Expressions, AngularJS directives, AngularJS Data Binding, AngularJS controllers, AngularJS modules, AngularJS scopes, filters, and more.

Additionally, we also provide AngularJS interview questions to help you deepen your understanding of the framework and prepare for potential job opportunities.

Key Points on AngularJS

  1. AngularJS is a JavaScript framework that is mainly used for Frontend Development.
  2. It is used for making Single Page Applications(SPA).
  3. It is open source and is completely free for everyone.
  4. It uses the Model, View, Control(MVC) pattern for developing projects.

Why use AngularJS?

  • Easy to work with: All you need to know to work with AngularJs is basics of HTML,CSS and Javascript,not necessary to be an expert in these technologies.
  • Time-saving: AngularJs allows us to work with components and hence we can use them again which saves time and unnecessary code.
  • Ready to use template: AngularJs is mainly plain HTML, and it mainly makes use of the plain HTML template and passes it to the DOM and then the AngularJS compiler. It traverses the templates and then they are ready to use.

Example:

<!DOCTYPE html>
<html>     
<head
    <title>AngularJS</title
    <script src= 
"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"> 
    </script
</head
<body style="text-align:center">  
    <h2 Hello World</h2
    <div ng-app="" ng-init="name='Hello World'"> 
        <p>{{ name }}.</p
    </div
</body
</html>  

Output:
Hello World

Introduction to AngularJS

AngularJS is a Javascript open-source front-end structural framework that is mainly used to develop single-page web applications(SPAs). It is a continuously growing and expanding framework which provides better ways for developing web applications. It changes the static HTML to dynamic HTML. Its features like dynamic binding and dependency injection eliminate the need for code that we have to write otherwise. AngularJS is rapidly growing and because of this reason, we have different versions of AngularJS with the latest stable being 1.7.9. It is also important to note that Angular is different from AngularJS. It is an open-source project which can be freely used and changed by anyone. It extends HTML attributes with Directives, and data is bound with HTML.

History of AngularJS: AngularJS was originally developed in 2008-2009 by Miško Hevery and Adam Abrons at Brat Tech LLC, as software for the online JSON storage service, in order to ease to development of the applications for the enterprise, that has been valued by the megabyte. It is now maintained by Google. AngularJS was released with version 1.6, which contains the component-based application architecture concept. This release version removed the Sandbox, which facilitates security, despite having the various vulnerabilities that have evolved, which bypassed the Sandbox.

 

Why use AngularJS?

  1. Easy to work with: All you need to know to work with AngularJS is the basics of HTML, CSS, and Javascript, not necessary to be an expert in these technologies.
  2. Time-saving: AngularJs allows us to work with components and hence we can use them again which saves time and unnecessary code.
  3. Ready to use a template: AngularJs is mainly plain HTML, and it mainly makes use of the plain HTML template and passes it to the DOM and then the AngularJS compiler. It traverses the templates and then they are ready to use.
  4. Directives: AngularJS’s directives allow you to extend HTML with custom elements and attributes. This enables you to create reusable components and define custom behaviors for your application. Directives make it easier to manipulate the DOM, handle events, and encapsulate complex UI logic within a single component.

Key Features: There are numerous features of AngularJS that contribute to creating efficient applications. Some of the features are described below:

  • Model View Controller(MVC): An architecture is basically a software pattern used to develop an application. It consists of three components: 
    1. Model: This component consists of a database & is responsible for managing the data & logic of the application. It responds to the request made by the View component & the instruction given by the Controller component, in order to update itself.
    2. View: This component is responsible for displaying the application data to the users. The View is basically the user interface that helps to render the required data to the user, with the help of the AngularJS expressions.
    3. Controller: This component is responsible for communicating & interacting between the Model & the View Component, i.e. its main job is to connect the model and the view component. It helps to validate the input data by implementing some business logic that manipulates the state of the data model.

Normally, when we talk about MVC architecture, we have to split our applications into these three components and then write the code to connect them. However, in AngularJS, all we have to do is split the application into MVC and it does the rest by itself. It saves a lot of time and allows you to finish the job with less code. 

  1. Data Model Binding: Data Binding in AngularJS is a two-way process, i.e. the view layer of the MVC architecture is an exact copy of the model layer. You don’t need to write special code to bind data to the HTML controls. Normally, in other MVC architectures, we have to continuously update the view layer and the model layer to remain in sync with one another. In AngularJs it can be said that the model layer and the view layer remain synchronized with each other. When the data in the model changes, then the view layer reflects the change and vice versa. It happens immediately and automatically which helps in making sure that the model and the view are updated at all times. 
  2. Templates: The main advantage of using AngularJS is how it makes use of the templates. Normally what happens is that the templates are passed by the browser into DOM, then DOM becomes the input of the AngularJS compiler and then AngularJS traverses the DOM template for rendering instructions which are called directives. The other siblings of AngularJS work differently as they make use of the HTML String whereas AngularJs does not manipulate the template strings. Using the DOM is what gives us the privilege to extend the directive vocabulary or even abstract them into reusable components.
  3. Unit Testing ready: The concern of Google’s designer was not only to develop Angular but also to develop a testing framework called “Karma” which helps in designing unit tests for AngularJS applications. 
  4. Integration and Extensibility: AngularJS can be easily integrated with other libraries and frameworks. It provides support for interacting with server-side APIs, handling HTTP requests, and integrating with third-party tools. AngularJS also allows you to extend its functionality by creating custom directives, filters, and services, giving you the flexibility to tailor the framework to your specific needs.

Benefits of AngularJS:

Depending Injection: Dependency Injection is a software design pattern. It works on the basis of Inversion of Control. Inversion control means objects do not create other objects. Instead, they get these objects from an outside source. The dependent object is not created by the primary object after that and then uses its methods. Instead, an external source creates the dependent object and gives it to the source object for further usage. On the basis of dependency injection, we create a service to acquire all the information from the database and get it into the model class. 

 

In Angular.JS, dependencies are injected by using an “injectable factory method” or “constructor function”. These components can be injected with “service” and “value” components as dependencies. The $http service is normally defined from within the controller in the following manner.

Pros of AngularJS:

  1. It facilitates the Two-way Binding that helps to render correspondingly the changes made to the view or the model.
  2. It helps to create a responsive web application, along with providing the prototyping that can be utilized to load the application faster.
  3. It uses the concept of directive that helps to add functionality to the application. For this, the overall length of the code reduces along with discarding the repetition of the code that is specific to perform the particular task.

Cons of AngularJS:

  1. As this framework belongs to Javascript, so it is required to have prior knowledge of Javascript.
  2. If new to this framework, then debugging the scope can be a difficult task.

AngularJS Modules

The AngularJS module defines the functionality of the application which is applied on the entire HTML page. It helps to link many components. So it is just a group of related components. It is a container that consists of different parts like controllers, services, and directives.

Note: These modules should be made in normal HTML files like index.html and no need to create a new project in VisualStudio for this section.

 

Creating a Module in AngularJS:

var app = angular.module("Module-name", []);

In this [], we can add a list of components needed but we are not including any components in this case. This created module is bound with any tag like div, body, etc by adding it to the list of modules.

<div ng-app = "module-name">
    The code in which the module is required.
</div>

Adding a Controller:

app.controller("Controller-name", function($scope) {
    $scope.variable-name= "";
});

Here, we can add any number of variables in the controller and use them in the HTML files, and the body of the tag in which the controller is added to that tag by writing:

<body>
    <div ng-app="Module-name">
        <div ng-controller="Controller-name">
            {{variable-name}}
        </div>
  
      <!-- This wont get printed since its
           not part of the div in which
           controller is included -->
        {{variable-name}}
    </div>
</body>

Module and Controllers in Files: While we can make modules and controllers in the same file along with the HTML file which requires it however we may want to use this module in some other file. Hence this will lead to redundancy so we will prefer to create Module, Controller, and HTML files separately. The Module and Controller are to be stored by using .js files and in order to use them in the HTML file we have to include them in this way:

Example 1: This example illustrates the implementation of the Angular JS Modules.

  • DemoController.js:
// Here the Component name is DemoComponent
// so saving the file as DemoComponent.js
app.controller('DemoController', function ($scope) {
  
    $scope.list = ['A', 'E', 'I', 'O', 'U'];
    $scope.choice = 'Your choice is: GeeksforGeeks';
  
    $scope.ch = function (choice) {
        $scope.choice = "Your choice is: " + choice;
    };
  
    $scope.c = function () {
        $scope.choice = "Your choice is: " + $scope.mychoice;
    };
});
  • Module-name: DemoApp.js:
var app = angular.module('DemoApp', []);
  • index.html file:
<!DOCTYPE html>
<html>
  
<head>
    <title>
        Modules and Controllers in Files
    </title>
    <script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js">
    </script>
    <script src="DemoApp.js"></script>
    <script src="DemoController.js"></script>
</head>
  
<body ng-app="DemoApp">
    <h1 style="color:green">GeeksforGeeks</h1>
    <h3>AngularJS Modules</h3>
    <h4>
        Using controllers in Module
    </h4>
  
    <div ng-app="DemoApp" 
         ng-controller="DemoController">
            Vowels List : 
        <button ng-click="ch('A')">A</button>
        <button ng-click="ch('E')">E</button>
        <button ng-click="ch('I')">I</button>
        <button ng-click="ch('O')">O</button>
        <button ng-click="ch('U')">U</button>
  
        <p>{{ choice }}</p>
  
        Vowels List :
        <select ng-options="option for option in list" 
                ng-model="mychoice" 
                ng-change="c()">
        </select>
  
        <p>{{ choice }}</p>
    </div>
</body>
  
</html>

Directives in a Module: To add a directive in a module follow the steps:

  • Creating a module as we did earlier:
var app = angular.module("DemoApp", []);
  • Creating a directive:
app.directive("Directive-name", function() {
    return {
        template : "string or some code which is to be executed"
    };
});

Example 2: This is another example illustrating the implementation of the AngularJS Module.

HTML

<!DOCTYPE html>
<html>
  
<head>
    <title>
        Modules and Controllers in Files
    </title>
  
    <script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js">
    </script>
</head>
  
<body>
    <div ng-app="GFG" w3-test-directive></div>
  
    <script>
        var gfg_app = angular.module("GFG", []);
        gfg_app.directive("w3TestDirective", function () {
            return {
                template: "Welcome to GeeksforGeeks!"
            };
        });
    </script>
</body>
  
</html>

Output:

Welcome to GeeksforGeeks!

AngularJS Controllers

In this article, we will see the Controller in AngularJS along with knowing how Controller works, the concept of the Controller method & how the Controller can be implemented in an external. We will understand all these aspects with the help of their implementation & accordingly will its illustrations.

AngularJS controllers play a significant role in AngularJS applications. All the AngularJS application mainly relies on the controllers to control the flow of data in that application. Basically, it controls the data of AngularJS applications and the controller is a Javascript object, created by a standard JavaScript object constructor.

 

The ng-controller directive defines the application controller. In AngularJS, a controller is defined by a Javascript construction function, which is used in AngularJS scope and also the function $scope) is defined when the controller is defining and it returns the concatenation of the $scope.firstname and $scope.lastname.

Syntax:

<element ng-controller="expression">
    Contents...
</element>

AngularJS Services

The Services is a function or an object that avails or limit to the application in AngularJS, ie., it is used to create variables/data that can be shared and can be used outside the component in which it is defined. Service facilitates built-in service or can make our own service. The Service can only be used inside the controller if it is defined as a dependency. In the case of many Services, the object that can be utilized, which is defined in DOM already, has few constraints in the AngularJS application. 

Why to use the AngularJS Service?

 

AngularJS supervise the application constantly. In order to handle the events or any changes in a proper manner, then the Service that is provided by the AngularJS will prefer to use, instead of Javascript Objects. For instance, the window.location object that is that already defined in the DOM, can be used with some limitations, likewise the $location service, in the AngularJS application. For this case, AngularJS generally prefer to use the $location service, instead of using the window.location object.

There are some commonly used built-in services, are described below:

  • $http Service: It makes the request to the server, in order to handle the response by the application.
  • $timeout Service: This service is AngularJS’ version of the window.setTimeout function.
  • $interval Service: This service is AngularJS’ version of the window.setInterval function.

Create the AngularJS Service:

STEP 1: Creating a service will follow the below command:

ng g s service-name

s is a short form for service. This creates two files service-name.service.spec.ts which is not supposed to be changed and service-name.service.ts.

STEP 2: After the service is created, we have to include it in the providers of app.module.ts

 
providers: [Service-nameService],

Here, the first letter of the service-name should be capitalized followed by Service written without any space.

STEP 3: So we have to now make changes in service-name.service.ts to create a JSON variable that is supposed to be made available to various components

Sailors = [22, ‘Dustin’, 7];

The sailors variable here is an array.

STEP 4: In app.component.ts make the following changes:

import the service among the rest of the required imports. Example:

import { Service-nameService } from './service-name.service';

just like the way we did it in providers.

Create a variable of any type: newData without mentioning any type.

In the constructor define a property of the Service type

constructor(private demoService: ServiceService) {}

Also, create a ngOnInit method:

ngOnInit(): void {
   this.newData=this.demoService.Sailors;

STEP 5: In app.component.html we will print the data stored in newData:

{{newData}}

Note: As we have added ngFor in app.component.html we will have to import FormsModule in app.module.ts

Example: This example describes the basic usage of the Services in angularJS.

 
import { Injectable } from "@angular/core";
  
@Injectable({
    providedIn: "root",
})
export class ServiceService {
    Sailors = [
        {
            id: 22,
            name: "Dustin",
            rating: 7,
        },
        {
            id: 29,
            name: "Brutus",
            rating: 1,
        },
        {
            id: 31,
            name: "Lubber",
            rating: 8,
        },
        {
            id: 32,
            name: "Andy",
            rating: 8,
        },
        {
            id: 58,
            name: "Rusty",
            rating: 10,
        },
        {
            id: 64,
            name: "Horatio",
            rating: 7,
        },
        {
            id: 71,
            name: "Zorba",
            rating: 10,
        },
        {
            id: 74,
            name: "Horatio",
            rating: 9,
        },
    ];
  
    constructor() { }
    getData() {
        return "This is the list of sailors" +
            " and their corresponding ratings";
    }
}
 
import { Component } from "@angular/core";
import { ServiceService } from "./service.service";
@Component({
    selector: "app-root",
    templateUrl: "./app.component.html",
    styleUrls: ["./app.component.css"],
})
export class AppComponent {
    newData;
    message: string = "";
    constructor(private demoService: ServiceService) { }
    ngOnInit(): void {
        this.newData = this.demoService.Sailors;
        this.message = this.demoService.getData();
    }
}
 
<div style="text-align:center; font-family:arial">
    <h1 style="color:green">GeeksforGeeks</h1>
    <h3>AngularJS Servies</h3>
    <h5>{{ message }}</h5>
    <p>ID Name Rating</p>
    <div *ngFor="let m of newData">
        <p>{{ m.id }} {{ m.name }} {{ m.rating }}</p>
    </div>
</div>

 

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
  
import { AppComponent } from './app.component';
  
@NgModule({
    imports: [BrowserModule, FormsModule],
    declarations: [AppComponent],
    bootstrap: [AppComponent],
})
export class AppModule { }