MODULE3 AngularJS
MODULE3 AngularJS
IT – TE –WEBX.0
Lecture -19
Samundiswary S
Designation
Dept. of Information Technology,
SIES Graduate School of Technology
1
Samundiswary S
Learning Objective
2
Samundiswary S
Introduction to AngularJs
• AngularJS is a JavaScript framework. It can be added to an HTML page with
a <script> tag.
• AngularJS extends HTML attributes with Directives, and binds data to HTML
with Expressions
• AngularJS is an open-source web application framework.
• It was originally developed in 2009 by Misko Hevery and Adam Abrons. It is
now maintained by Google.
• AngularJS is a structural framework for dynamic web applications. It lets you
use HTML as your template language and lets you extend HTML's syntax to
express your application components clearly and succinctly.
• Its data binding and dependency injection eliminate much of the code you
currently have to write. And it all happens within the browser, making it an
ideal partner with any server technology.
Samundiswary S
Need of AngularJs
• AngularJS is an efficient framework that can create Rich Internet Applications
(RIA).
Samundiswary S
AngularJs Environment setup
• To download AngularJS -open the link https://angularjs.org/
• CDN access − You also have access to a CDN. The CDN gives you access to
regional data centers. In this case, the Google host. The CDN transfers the
responsibility of hosting files from your own servers to a series of external ones. It
also offers an advantage that if the visitor of your web page has already downloaded
a copy of AngularJS from the same CDN, there is no need to re-download it.
Samundiswary S
AngularJS vs Angular
6
Samundiswary S
Key Features of Angular JS
7
Samundiswary S
Key Features of Angular JS
8
Samundiswary S
Key Features of Angular JS
9
Samundiswary S
Key Features of Angular JS
10
Samundiswary S
AngularJS MVC Architecture
• MVC as it is popularly called, is a software design pattern for developing web
applications. A Model View Controller pattern is made up of the following
three parts −
• Model − It is the lowest level of the pattern responsible for maintaining data.
• View − It is responsible for displaying all or a portion of the data to the user.
• Controller − It is a software Code that controls the interactions between the
Model and View.
Samundiswary S
MVC Architecture in AngularJS
12
Samundiswary S
AngularJS MVC Architecture
The Model:
• Model part consists of a database (use to store data), application data
(application data are variables that are specific to a user. Application and
logic (Logic refers to code that is written to perform a certain task).
The View:
• A presentation of data in a particular format, triggered by the controller's
decision to present the data. They are script-based template systems such
as JSP, ASP, PHP and very easy to integrate with AJAX technology.
The Controller:
• The controller responds to user input and performs interactions on the data
model objects. The controller receives input, validates it, and then performs
business operations that modify the state of the data model.
Samundiswary S
AngularJS MVC Architecture
Samundiswary S
Benefits of MVC
15
Samundiswary S
Benefits of MVC
16
Samundiswary S
Advantages of AngularJS over other JavaScript
frameworks
• Dependency Injection: Dependency Injection specifies a design pattern in which
components are given their dependencies instead of hard coding them within the
component.
• Two way data binding: In two way data binding, any changes to the model are immediately
reflected in the View and any changes in the View updates the model.
• Testing: Angular JS is designed in a way that we can test right from the start. So, it is very
easy to test any of its components through unit testing and end-to-end testing.
• Model View Controller: In Angular JS, it is very easy to develop application in a clean MVC
way. You just have to split your application code into MVC components i.e. Model, View and
the Controller.
• Directives, filters, modules, routes etc.
17
Samundiswary S
Module-3 AngularJs
IT – TE –WEBX.0
Lecture -20
Samundiswary S
Designation
Dept. of Information Technology,
SIES Graduate School of Technology
18
Samundiswary S
AngularJS First Application
• An AngularJS application consists of following three important parts −
• ng-app − This directive defines and links an AngularJS application to HTML.
• ng-model − This directive binds the values of AngularJS application data to
HTML input controls.
• ng-bind − This directive binds the AngularJS Application data to HTML tags.
Samundiswary S
AngularJS Expressions
• AngularJS binds data to HTML using Expressions.
• AngularJS Expressions
AngularJS expressions can be written inside double braces: {{ expression }}.
AngularJS expressions can also be written inside a directive:
ng-bind="expression".
AngularJS will resolve the expression, and return the result exactly where the
expression is written.
AngularJS expressions are much like JavaScript expressions: They can
contain literals, operators, and variables.
Example {{ 5 + 5 }} or {{ firstName + " " + lastName }}
Samundiswary S
AngularJS Expressions on numbers
Total in dollar: 5
Samundiswary S
AngularJS Expressions on AngularJS Objects
Samundiswary S
AngularJS Expressions vs. JavaScript Expressions
Samundiswary S
AngularJS modules
Samundiswary S
Adding a Controller to module
25
Samundiswary S
AngularJS Directives
AngularJS lets you extend HTML with new attributes called Directives.
AngularJS has a set of built-in directives which offers functionality to your applications.
ng-model −The ng-model directive binds the value of HTML controls (input, select, textarea)
to application data
ng-repeat − This directive repeats HTML elements for each item in a collection.
26
Samundiswary S
AngularJS Directives
ng -model:
The ng-model directive binds the value of HTML controls (input, select, textarea) to
application data.
27
Samundiswary S
AngularJS Directives-ng-repeat example
28
Samundiswary S
ng-show
• The ng-show Directive in AngluarJS is used to show or hide the specified HTML element. If the given
expression in the ng-show attribute is true then the HTML element will display otherwise it hides the
HTML element. It is supported by all HTML elements.
Syntax:
<element ng-show="expression">
Contents...
</element>
Parameter Value:
• expression: It specifies the element will be displayed only if the required expression returns true.
29
Samundiswary S
ng-hide
• The ng-hide directive hides the HTML element if the expression evaluates to true.
• ng-hide is also a predefined CSS class in AngularJS, and sets the element's display to none.
30
Samundiswary S
AngularJS Directives list
https://docs.angularjs.org/api/ng/directive
31
Samundiswary S
AngularJS custom Directives
New directives are created by using the .directive function.
To invoke the new directive, make an HTML element with the same tag name as the new
directive.
When naming a directive, you must use a camel case name, w3TestDirective, but when
invoking it, you must use - separated name, w3-test-directive:
• Element name
• Attribute
• Class
• Comment
32
Samundiswary S
Create your own Directives
33
Samundiswary S
Directives Restrictions
You can restrict your directives to only be invoked by some of the methods.
By adding a restrict property with the value "A", the directive can only be invoked by attributes:
The legal restrict values are:
34
Samundiswary S
Module-3 AngularJs
IT – TE –WEBX.0
Lecture -21
Samundiswary S
Designation
Dept. of Information Technology,
SIES Graduate School of Technology
35
Samundiswary S
AngularJs Controller
• The controller in AngularJS is a JavaScript function that maintains the
application data and behavior using $scope object.
• You can 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 used to specify a controller in HTML element,
which will add behavior or maintain the data in that HTML element and its
child elements.
Samundiswary S
AngularJs Controller
• To create "myController", we need to create an application module. The module defines an
application and keeps its parts like controllers, services etc. out of global scope.
• After creating a module, we add a controller function using the controller() method where the
first parameter should be the name of the controller and second parameter should be a
function for the controller.
• The controller function includes $scope parameter which will be injected by AngularJS
framework.
• AngularJS framework injects $scope object to each controller function. It also injects other
services if included as a parameter of controller function.
• The $ sign is used as prefix in all the built-in objects in AngularJS, so that we can differentiate
AngularJS built-in objects and other objects.
• For every controller, angular creates or injects $scope object in angular. Therefore, the
behavior attached in one controller cannot be accessed by another controller in AngularJS.
37
Samundiswary S
Scope in AngularJS
The $scope in an AngularJS is a built-in object, which 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.
38
Samundiswary S
AngularJS Controller-example
Name of the
controller
property of
studentController
object
properties of
$scope.student object
Samundiswary S
Angularjs Data binding
Data binding is the synchronization of data between business logic and view of the
application. It serves as a bridge between two components of angular that is model part
and view part. Data Binding is automatic and provides a way to wire the two important part
of an application that is the UI and application data.
Whenever some changes are done at the model side it is reflected at view side too and
vice versa is also possible. This happens so rapidly to make sure that view and the model
part will get update all the time.
One Way Data Binding:
In one-way data binding, the flow of data restricts to one side only and that is from model to
view. It follows a unidirectional approach. In the case of updating in the model part, same
will sync in the view part also but the vice versa is not possible as in one way binding data
can’t flow from view to model.
Interpolation binding (an expression is taken as an input and it is changed as a text using
HTML elements), property binding (Value of a property is set on an HTML element) comes
in the category of one-way data binding in AngularJS.
40
Samundiswary S
Angularjs Data binding
41
Samundiswary S
AngularJS Data Binding
Data binding in AngularJS is the synchronization between the model and the view.
Data Model:
AngularJS applications usually have a data model. The data model is a collection of data
available for the application.
HTML View
The HTML container where the AngularJS application is displayed, is called the view.
The view has access to the model, and there are several ways of displaying model data in the
view.
You can use the ng-bind directive, which will bind the innerHTML of the element to the specified
model property:
You can also use double braces {{ }} to display content from the model:
You can use the ng-model directive on HTML controls to bind the model to the view.
42
Samundiswary S
AngularJS Data Binding using ng-bind
43
Samundiswary S
AngularJS ng-model Directive
With the ng-model directive you can bind the value of an input field to a variable created in AngularJS.
Two-Way Binding:
The binding goes both ways. If the user changes the value inside the input field, the AngularJS
property will also change its value:
44
Samundiswary S
AngularJS ng-model Directive
Validate User Input
The ng-model directive can provide type validation for application data (number, e-mail, required):
45
Samundiswary S
AngularJS ng-model Directive
Application Status
The ng-model directive can provide status for application data (valid, dirty, touched, error):
46
Samundiswary S
Module-3 AngularJs
IT – TE –WEBX.0
Lecture -22
Samundiswary S
Designation
Dept. of Information Technology,
SIES Graduate School of Technology
47
Samundiswary S
AngularJS Filters
In AngularJS, filters are used to format data. Following is a list of filters used for transforming data.
48
Samundiswary S
Adding filters to expressions and directives
Filters can be added to expressions by using the pipe character |, followed by a filter.
Filters are added to directives, like ng-repeat, by using the pipe character |, followed by a filter:
Filter applied
on expression
Filter applied
on Directive
ng-repeat
49
Samundiswary S
Filter applied on Directive ng-repeat
50
Samundiswary S
The filter Filter
The filter filter selects a subset of an array.
The filter filter can only be used on arrays, and it returns an array containing only the matching items.
51
Samundiswary S
Sort an array based on user input
By adding the ng-click directive on the table headers, we can run a function that changes the
sorting order of the array:
52
Samundiswary S
Custom Filter
You can make your own filters by registering a new filter factory function with your module:
53
Samundiswary S
Custom Filter
Output:
54
Samundiswary S
AngularJS scope
The Scope is an object that is specified as a binding part between the HTML (view)
and the JavaScript (controller).
It plays a role of joining controller with the views. It is available for both the view and
the controller.
To make a controller in AngularJS, you have to pass the $scope object as an
argument.
The scope is a JavaScript object with properties and methods, which are available for
both the view and the controller.
55
Samundiswary S
AngularJS scope example
56
Samundiswary S
AngularJS Root scope
• All applications have a $rootScope which is the scope created on the HTML
element that contains the ng-app directive.
• If a variable has the same name in both the current scope and in the
rootScope, the application uses the one in the current scope.
• The $rootScope is the top-most scope. An app can have only one
$rootScope which will be shared among all the components of an app. Hence
it acts like a global variable. All other $scopes are children of the $rootScope.
57
Samundiswary S
AngularJS Root scope
Output:
58
Samundiswary S
Module-3 AngularJs
IT – TE –WEBX.0
Lecture -23
Samundiswary S
Designation
Dept. of Information Technology,
SIES Graduate School of Technology
59
Samundiswary S
Dependency Injection
60
Samundiswary S
Dependency Injection
So before getting to dependency injections, first let’s understand what a dependency in
programming means.
When class A uses some functionality of class B, then its said that class A has a
dependency of class B.
61
Samundiswary S
62
Samundiswary S
Need of Dependency Injection
• A car class which contains various objects such as wheels, engine, etc
• Car class is responsible for creating all the dependency objects. Now, what
if we decide to ditch MRFWheels in the future and want to use Yokohama
Wheels.
• Need to recreate the car object with a new Yokohama dependency.
• But when using dependency injection (DI), we can change the Wheels at
runtime (because dependencies can be injected at runtime rather than at
compile time).
• DI as the middleman in our code who does all the work of creating the
preferred wheels object and providing it to the Car class.
• Makes our Car class independent from creating the objects of Wheels,
Battery, etc
63
Samundiswary S
Dependency Injection types
64
Samundiswary S
AngularJS Dependency Injection
AngularJS comes with a built-in dependency injection mechanism that enables you to
divide your application into various types of components which can be injected into each
other as their respective dependencies.
Modularization of your application makes it easier to use, reuse, configure and even test
the different components in your application. According to DI the core types of objects and
components include the following:
• Value
• Factory
• Service
• Provider
• Constant
These are the objects and components which can be injected into each other using
AngularJS Dependency Injection.
65
Samundiswary S
AngularJS Dependency Injection-value
• In AngularJS, value is a simple object. It can be a number, string or JavaScript
object. It is used to pass values in factories, services or controllers during run
and config phase.
Injecting a value
To inject a value into AngularJS controller function, add a parameter with the same when the value
is defined.
66
Samundiswary S
AngularJS Dependency Injection-factory
• Factory is a function that is used to return value. When a service or controller
needs a value injected from the factory, it creates the value on demand. It
normally uses a factory function to calculate and return the value.
67
Samundiswary S
AngularJS Dependency Injection-Services &
Providers
Web Services are helpful functions that perform a task. Similarly, in AngularJS, Service is
a JavaScript object which contains a set of functions to perform certain tasks. Services are
created by using service() function on a module and then injecting it into controllers.
Provider is used by AngularJS internally to create services, factory, etc. during the config
phase. Provider is a special factory method with get() method which is used to return the
value/service/factory.
68
Samundiswary S
Bootstrapping process
69
Samundiswary S
Bootstrapping process
70
Samundiswary S
Phases of Bootstrapping in AngularJS
1. Loading Phase:
This is the first phase where the AngularJS framework is loaded into the
browser.Steps:The browser loads the HTML document.The AngularJS library is
loaded via a <script> tag.
The AngularJS module (defined using angular.module()) is registered.The
browser parses the DOM (Document Object Model).
2. Compilation Phase
In this phase, AngularJS compiles the DOM to identify directives (ng-app, ng-
controller, ng-model, etc.), binds them with the scope, and creates the
necessary structure for data binding.
Steps:Detect ng-app directive: AngularJS identifies the root element (ng-app)
to initialize the application.
Create Injector: Angular creates the dependency injection system.
Compile DOM: It scans the DOM, finds directives, and links them with the
respective scope.
71
Samundiswary S
Phases of Bootstrapping in AngularJS
3. Linking Phase
This phase establishes the relationship between the compiled DOM
and the scope.
Steps:The compiled directives are linked with the corresponding
scope.
Two-way data binding is established.
Any event listeners (ng-click, ng-change) are attached.
4. Execution (Runtime) Phase
This is the phase where AngularJS starts executing the actual
application logic.
Steps:AngularJS initializes the config phase.
Controllers, services, and directives execute.$digest cycle runs to
track scope changes and update the UI.
72
Samundiswary S
AngularJS Dependency Injection-Services
73
Samundiswary S
AngularJS Dependency Injection-Provider
Provider is used by AngularJS internally to configure services, factory, etc. during the
config phase. The following script can be used to create MathService that we created
earlier. Provider is a special factory method with get() method which is used to return
the value/service/factory.
74
Samundiswary S
AngularJS Dependency Injection-constants
You cannot inject values into the module.config() function. Instead constants are
used to pass values at config phase.
Constants in AngularJS are defined using the module.constants() function. Here is an
AngularJS constant example:
This constant can now be injected into the module.config() function like this:
75
Samundiswary S
Module-3 AngularJs
IT – TE –WEBX.0
Lecture -24
Samundiswary S
Designation
Dept. of Information Technology,
SIES Graduate School of Technology
76
Samundiswary S
AngularJS services
77
Samundiswary S
AngularJS services
built-in AngularJS services
All the Angular services are lazy instantiated and singleton. It means AngularJS
framework instantiates a service when an application component depends on it.
Also, all the components share the same instance of a service.
78
Samundiswary S
AngularJS $location service
• The $location service has methods which return information about the location
of the current web page:
79
Samundiswary S
The $http Service
The $http service is one of the most common used services in AngularJS applications. The
service makes a request to the server, and lets your application handle the response.
$http is a service as an object. It includes following shortcut methods.
80
Samundiswary S
$http service
The AngularJS $http service makes a request to the server, and returns a response.
81
Samundiswary S
$http.get()
$http.get() method sends http GET request to the remote server and retrieves the data.
$http.get() method returns HttpPromise object, which includes various methods to process the
response of http GET request.
$http.post
The $http.post() method sends Http POST request to the remote server to submit and retrieve
the data.
82
Samundiswary S
$http Properties
The response from the server is an object with these properties:
83
Samundiswary S
$window Service
AngularJs includes $window service which refers to the browser window object.
In the JavaScript, window is a global object which includes many built-in methods like alert(),
prompt() etc.
The $window service is a wrapper around window object, so that it will be easy to override,
remove or mocked for testing. It is recommended to use $window service in AngularJS instead
of global window object directly.
84
Samundiswary S
$log service
AngularJS includes a logging service called $log, which logs the messages to the
client browser's console.
The $log service includes different methods to handle the log for error, information,
warning or debug information. It can be useful in debugging and auditing.
The main purpose of all AngularJS logging services is to simplify debugging and
troubleshooting.
To reveal the location of the calls to $log in the JavaScript console; you can "blackbox"
the AngularJS source in your favorite browser. To blackbox in the browser, go to the
page, right click it, “Inspect” it in developer mode, and then read the console.
Some methods that we will use for logging in AngularJS $log are:
85
Samundiswary S
$log service example
86
Samundiswary S
Module-3 AngularJs
IT – TE –WEBX.0
Lecture -25
Samundiswary S
Designation
Dept. of Information Technology,
SIES Graduate School of Technology
87
Samundiswary S
Form Validation
Create a HTML form and apply client side validation using AngularJS
88
Samundiswary S
State properties
• Angular includes properties which return the state of form and input controls. The state of the
form and control changes based on the user's interaction and validation errors.
• These built-in properties can be accessed using form name or input control name.
• To check the form status use formName.propertyName, and to check the state of input control,
use formName.inputFieldName.propertyName.
89
Samundiswary S
ng-view
• AngularJS View is a content which is displayed to the user. According to a user
request, the view of an application is displayed to the user. Since in one single
page application, it can have a number of views. Therefore, according to the
user’s choice, a view is shown.
• Using the combination of views and routes, an application can be divided in
logical views and bind different views to controllers.
• Our application become more manageable by dividing it into different views and
using routing to load different views of an application.
• For example, we have a registration application, in which an admin can add
new students and view students.
90
Samundiswary S
ng-view
• ng- view is a directive that works like a placeholder. It creates a placeholder
where a corresponding view can be placed based on the configuration. Here, a
view can be HTML or ng-template view.
IT – TE –WEBX.0
Lecture -26
Samundiswary S
Designation
Dept. of Information Technology,
SIES Graduate School of Technology
92
Samundiswary S
Routing using ng-Route
• The ngRoute module helps your application to become a Single Page Application
Routing in angularJS:
• If you want to navigate to different pages in your application, but you also want
the application to be a SPA (Single Page Application), with no page reloading,
you can use the ngRoute module.
• The ngRoute module routes your application to different pages without reloading
the entire application
• This routing module acts based on the url. When a user requests a specific url,
the routing engine captures that url and renders the view based on the defined
routing rules.
93
Samundiswary S
What is Single Page Applications?
• Single Page Applications (SPAs) are web applications that will works or loads on a single
HTML page and dynamically update the page based on user interaction.
• That means, changing the content on what we want to route.
• The SPA only sends what you need with each click, and your browser renders that
information. This is different than a traditional page load where the server re-renders a full
page with every click you make and sends it to your browser.
• This piece-by-piece, client-side method makes load time much faster for users and makes
the amount of information a server has to send a lot less and a lot more cost efficient. A win-win.
94
Samundiswary S
AngularJS Routing
• AngularJS ngRoute module provides routing, deep linking services and directives
for angular applications.
• We have to download angular-route.js script that contains the ngRoute module
from AngularJS official website to use the routing feature
• You can also use the CDN in your application to include this file. In this tutorial,
We are going to use the Google CDN.
• If you want to include it from Google CDN, then use below code.
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.28//angular-
route.min.js"></script>
• Then load the ngRoute module in your AngularJS application by adding it as a
dependent module as shown below.
angular.module('appName', ['ngRoute’]);
ngView:
ngView directive is used to display the HTML templates or views in the specified
routes. Every time the current route changes, the included view changes with it
according to the configuration of the $route service.
95
Samundiswary S
AngularJS Routing
$routeProvider:
• $routeProvider is used to configure the routes. We use the ngRoute config() to
configure the $routeProvider. The config() takes a function which takes the
$routeProvider as parameter and the routing configuration goes inside the
function.
• $routeProvider has a simple API, accepting either the when() or otherwise()
method.
AngularJS Routing Syntax:
96
Samundiswary S
AngularJS Routing Example
• Create a module named myApp and load ngRoute as a dependent module.
• Configure the routes using $routeProvider.
• We use three paths in the example, /index , /delhi and /mumbai.
• We use controller in this example, delhiCtrl and mumbaiCtrl
97
Samundiswary S
AngularJS Routing Example
The URL part after the # matches /index, it will load index.html page and if it
matches /mumbai then it will load mumbai.html in to the shell page.
if it matches /delhi then it will load delhi.html in to the shell page
98
Samundiswary S
ng-style
The ng-style Directive in AngularJS is used to apply custom CSS styles on an HTML
element.
The expression inside the ng-style directive must be an object. It is supported by all the
HTML elements.
Syntax:
<element ng-style="expression"> Content ... </element>
• ngStyle becomes much more useful when the value is dynamic.
• The values in the object literal that we assign to ngStyle can be JavaScript
expressions which are evaluated and the result of that expression is used as the
value of the CSS property, like this:
The above code uses the ternary operator to set the background color to green if the
persons country is the UK else red.
99
Samundiswary S
ng-style example
100
Samundiswary S
Built-in Helper functions
101
Samundiswary S
Built-in Helper Functions
AngularJS Copy:
AngularJS copy function is intended to creates a deep copy of source object or array and
assign it to destination where destination is optional
Syntax:
angular.copy(source, [destination]);
AngularJS equals:
The angular.equals function compares and determines if 2 objects or values are equal,
angular.equals performs a deep comparison and returns true if and only if at least 1 of the
following conditions is met.
angular.equals(value1, value2)
102
Samundiswary S
Built-in Helper Functions
AngularJS forEach:
The angular.forEach accepts an object and an iterator function. It then runs the iterator function
over each enumerable property/value of the object. This function also works on arrays.
AngularJS fromJson
The function angular.fromJson will deserialize a valid JSON string and return an Object or an
Array.
angular.fromJson(string|object)
Note that this function is not limited to only strings, it will output a representation of any object
passed to it.
103
Samundiswary S
Built-in Helper functions
angular.identity
The angular.identity function returns the first argument passed to it.
angular.identity(argument)
This function is useful for functional programming, you can provide this function as a default
in case an expected function was not passed.
angular.isArray:
The angular.isArray function returns true if and only if the object or value passed to it is of
the type Array.
angular.isArray(value)
Angular.isDate
The angular.isDate function returns true if and only if the object passed to it is of the type
Date.
angular.isDate(value)
angular.isFunction:
The function angular.isFunction determines and returns true if and only if the value passed to
is a reference to a function.
The function returns a reference to the now extended destination object
angular.isFunction(fn)
104
Samundiswary S
Built-in Helper functions
angular.merge:
The function angular.merge takes all the enumerable properties from the source object to
deeply extend the destination object.
angular.merge(destination, source)
Link: https://riptutorial.com/angularjs/topic/3032/built-in-helper-functions
105
Samundiswary S