Introduction to AngularJS
Prepared by Prof. Martina D'souza , IT dept 1
What is AngularJS?
• AngularJS was a JavaScript-based open-source front-end web
framework for developing single-page applications.
• It was maintained mainly by Google and a community of
individuals and corporations.
• It aimed to simplify both the development and the testing of such
applications by providing a framework for client-side model–
view–controller (MVC) and model–view–viewmodel (MVVM)
architectures, along with components commonly used in web
applications and progressive web applications.
• AngularJS was used as the frontend of the MEAN stack, that
consisted of MongoDB database, Express.js web application
server framework, AngularJS itself (or Angular),
and Node.js server runtime environment.
Prepared by Prof. Martina D'souza , IT dept 2
What is AngularJS?
• AngularJS is a structural framework for dynamic web applications.
• It allows to split the business logic layer, data layer, and
presentation layer.
• It uses HTML as a template language to extend its syntax for
creating various application components.
• It also helps to reduce the code by data binding and dependency
injection features.
• Dependency injection refers to the passing of objects between the
application and the client.
Prepared by Prof. Martina D'souza , IT dept 3
Features
• AngularJS is a efficient framework that can create Rich Internet
Applications (RIA).
• AngularJS provides developers an options to write client side
applications using JavaScript in a clean Model View Controller
(MVC) way.
• Applications written in AngularJS are cross-browser compliant.
• AngularJS automatically handles JavaScript code suitable for each
browser.
• 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.
Prepared by Prof. Martina D'souza , IT dept 4
Core features
• Data-binding: It is the automatic synchronization of data between
model and view components.
• Scope: These are objects that refer to the model. They act as a glue
between controller and view.
• Controller: These are JavaScript functions bound to a particular
scope.
• Services: AngularJS comes with several built-in services such as
$http to make a XMLHttpRequests. These are singleton objects
which are instantiated only once in app.
• Filters: These select a subset of items from an array and returns a
new array.
• Directives: Directives are markers on DOM elements such as
elements, attributes, css, and more. These can be used to create
custom HTML tags that serve as new, custom widgets. AngularJS
has built-in directives such as ngBind, ngModel, etc.
Prepared by Prof. Martina D'souza , IT dept 5
• Templates: These are the rendered view with information from the
controller and model. These can be a single file (such as
index.html) or multiple views in one page using partials.
• Routing: It is concept of switching views.
• Model View Whatever: MVW is a design pattern for dividing an
application into different parts called Model, View, and Controller,
each with distinct responsibilities. AngularJS does not implement
MVC in the traditional sense, but rather something closer to
MVVM (Model-View-ViewModel).
• The Angular JS team refers it humorously as Model View
Whatever.
• Deep Linking: Deep linking allows to encode the state of
application in the URL so that it can be bookmarked. The
application can then be restored from the URL to the same state.
• Dependency Injection: AngularJS has a built-in dependency
injection subsystem that helps the developer to create, understand,
and test the applications easily.
Prepared by Prof. Martina D'souza , IT dept 6
• As developers, we just have to split our code into the model,
view, and controller and the rest of the operations such as
managing the components and connecting them together will
be automatically donePrepared
by AngularJS.
by Prof. Martina D'souza , IT dept 7
MVC
• The Controller represents the layer that has the business logic.
• User events trigger the functions which are stored inside your
controller.
• The user events are part of the controller.
• The controller receives input, validates it, and then performs
business operations that modify the state of the data model.
• Views are used to represent the presentation layer which is
provided to the end users.
• It also specifies the 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.
Prepared by Prof. Martina D'souza , IT dept 8
• Models are used to represent your data.
• The data in your model can be as simple as just having primitive
declarations.
• It responds to the requests from view and to the instructions from
controller to update itself.
• For example, if you are maintaining a student application, your
data model could just have a student id and a name. Or it can also
be complex by having a structured data model.
• Two-way Data Binding
• Software changes should be responsive, and changes within the
system should be catered to the changes in the user interface and
conversely, with precision and speed.
• AngularJS offers this kind of binding by synchronizing between
the model and the view.
Prepared by Prof. Martina D'souza , IT dept 9
Advantages of AngularJS
• It provides the capability to create Single Page Application in a
very clean and maintainable way.
• It provides data binding capability to HTML, giving user a rich
and responsive experience.
• AngularJS code is unit testable.
• AngularJS uses dependency injection and make use of separation
of concerns.
• AngularJS provides reusable components.
• With AngularJS, the developers can achieve more functionality
with short code.
• In AngularJS, views are pure html pages, and controllers written
in JavaScript do the business processing.
• AngularJS applications can run on all major browsers and smart
phones, including Android and iOS based phones/tablets.
Prepared by Prof. Martina D'souza , IT dept 10
Disadvantages of AngularJS
• Not secure : Being JavaScript only framework, application written
in AngularJS are not safe.
• Server side authentication and authorization is must to keep an
application secure.
• Not degradable: If the user of application disables JavaScript, then
nothing would be visible, except the basic page.
Prepared by Prof. Martina D'souza , IT dept 11
Please note
• AngularJS:
• Does not support conditionals, loops, and exceptions in
expressions.
• Does not support function declaration (even inside the ng-init
directive) in expressions.
• Does not support bitwise, comma, void and new operator in
expressions.
• Ignores the null or undefined properties in expressions.
• Expressions are evaluated belonging to the scope object and
not the global window.
Prepared by Prof. Martina D'souza , IT dept 12
AngularJS - Environment Setup
• Go to https://angularjs.org/
• Click Download AngularJs
Prepared by Prof. Martina D'souza , IT dept 13
• CDN access − 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.
• For Offline download.. Click download and copy paste the file.
angular.min.js
Prepared by Prof. Martina D'souza , IT dept 14
<!doctype html>
<html>
<head>
<script src =
"https://ajax.googleapis.com/ajax/libs/angularjs/1.5.2/angular.min.js">
</script>
</head>
Or
<script src="js/angular.min.js"></script>
</head>
Prepared by Prof. Martina D'souza , IT dept 15
AngularJS Directives
• The AngularJS framework can be divided into three major
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.
• ng-init − This directive initializes application data.
• ng-repeat − This directive repeats HTML elements for each
item in a collection.
Prepared by Prof. Martina D'souza , IT dept 16
Include in html file
• Define AngularJS application using ng-app directive
• <div ng-app = ""> ... </div>
• Define a model name using ng-model directive
• <p>Enter your Name: <input type = "text" ng-model =
"name"></p>
• Bind the value of above model defined using ng-bind directive
• <p>Hello <span ng-bind = "name"></span>!</p>
Prepared by Prof. Martina D'souza , IT dept 17
<html>
Index.html
<head>
<title>AngularJS First Application</title>
<script src =
"https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
</script>
</head>
<body>
<h1>Sample Application</h1>
<div ng-app = "">
<p>Enter your Name: <input type = "text" ng-model = "name"></p>
<p>Hello <span ng-bind = "name"></span>!</p>
</div>
</body>
</html>
Prepared by Prof. Martina D'souza , IT dept 18
Building blocks of AngularJs
Prepared by Prof. Martina D'souza , IT dept 19
How AngularJS Integrates with HTML
• The ng-app directive indicates the start of AngularJS application.
• The ng-model directive creates a model variable named name,
which can be used with the HTML page and within the div having
ng-app directive.
• The ng-bind then uses the name model to be displayed in the
HTML <span> tag whenever user enters input in the text box.
• Closing</div> tag indicates the end of AngularJS application.
Prepared by Prof. Martina D'souza , IT dept 20
ng-app directive
• The ng-app directive starts an AngularJS Application.
• It defines the root element.
• It automatically initializes or bootstraps the application when the
web page containing AngularJS Application is loaded.
• It is also used to load various AngularJS modules in AngularJS
Application.
<div ng-app = "">
...
</div>
Prepared by Prof. Martina D'souza , IT dept 21
ng-model directive
• The ng-model directive defines the model/variable to be used
in AngularJS Application.
• In the following example, we define a model named name.
<div ng-app = "">
...
<p>Enter your Name: <input type = "text" ng-model =
"name"></p>
</div>
Prepared by Prof. Martina D'souza , IT dept 22
ng-init directive
• The ng-init directive initializes an AngularJS Application data.
• It is used to assign values to the variables.
• In the following example, we initialize an array of countries.
• JSON syntax to define the array of countries.
<div ng-app = "" ng-init = "countries = [{locale:'en-
US',name:'United States'}, {locale:'en-GB',name:'United
Kingdom'}, {locale:'en-FR',name:'France'}]">
...
</div>
Prepared by Prof. Martina D'souza , IT dept 23
ng-repeat directive
• The ng-repeat directive repeats HTML elements for each item in a
collection.
• In the following example, we iterate over the array of countries.
<div ng-app = "">
...
<p>List of Countries with locale:</p>
<ol>
<li ng-repeat = "country in countries">
{{ 'Country: ' + country.name + ', Locale: ' + country.locale }}
</li>
</ol>
</div>
Prepared by Prof. Martina D'souza , IT dept 24
Index.html
<div ng-app = "" ng-init = "countries = [{locale:'en-US',name:'United States'},
{locale:'en-GB',name:'United Kingdom'}, {locale:'en-FR',name:'France'}]">
<p>Enter your Name: <input type = "text" ng-model = "name"></p>
<p>Hello <span ng-bind = "name"></span>!</p>
<p>List of Countries with locale:</p>
<ol>
<li ng-repeat = "country in countries">
{{ 'Country: ' + country.name + ', Locale: ' + country.locale }}
</li>
</ol>
</div>
Prepared by Prof. Martina D'souza , IT dept 25
• ng-if
• The ng-if directive creates or removes an HTML element based on
the Boolean value returned from the specified expression.
• If an expression returns true then it recreates an element otherwise
removes an element from the HTML document.
• ng-readonly
• The ng-readonly directive makes an HTML element read-only,
based on the Boolean value returned from the specified expression.
If an expression returns true then the element will become read-
only, otherwise not.
• ng-disabled
• The ng-disabled directive disables an HTML element, based on the
Boolean value returned from the specified expression. If an
expression returns true the element will be disabled, otherwise not.
Prepared by Prof. Martina D'souza , IT dept 26
AngularJS Directives List
• AnglarJS directives are used to add functionality to your
application.
• https://www.javatpoint.com/angularjs-directives
Prepared by Prof. Martina D'souza , IT dept 27
AngularJS - Expressions
• Expressions are used to bind application data to HTML.
• Expressions are written inside double curly braces such as in {{
expression}}.
• Expressions behave similar to ngbind directives.
• AngularJS expressions are pure JavaScript expressions and output the
data where they are used.
• {{ 5 + 5 }} or {{ firstName + " " + lastName }}
• Using numbers
• <p>Expense on Books : {{cost * quantity}} Rs</p>
• Using Strings
• <p>Hello {{student.firstname + " " + student.lastname}}!</p>
• Using Object
• <p>Roll No: {{student.rollno}}</p>
• Using Array
• <p>Marks(Math): {{marks[3]}}</p>
Prepared by Prof. Martina D'souza , IT dept 28
Simple eg
<!DOCTYPE html>
<html>
<script
src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular
.min.js"></script>
<body>
<div ng-app>
<p>A simple expression example: {{ 5 + 5 }}</p>
</div>
</body>
</html>
Prepared by Prof. Martina D'souza , IT dept 29
<html>
<head>
<title>AngularJS Expressions</title> </head>
<body>
<h1>Sample Application</h1>
<div ng-app = "" ng-init = "quantity = 1;cost = 30;
student = {firstname:'Mahesh',lastname:'Parashar',rollno:101};
marks = [80,90,75,73,60]">
<p>Hello {{student.firstname + " " + student.lastname}}!</p>
<p>Expense on Books : {{cost * quantity}} Rs</p>
<p>Roll No: {{student.rollno}}</p>
<p>Marks(Math): {{marks[3]}}</p>
</div>
<script src =
"https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
</script>
</body> </html> Refer Expr.html
Prepared by Prof. Martina D'souza , IT dept 30
Example to change the color of input box by changing its value.
<!DOCTYPE html>
<html>
<script
src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></scri
pt>
<body>
<p>Change the value of the input field:</p>
<div ng-app="" ng-init="myCol='pink'">
<input style="background-color:{{myCol}}" ng-model="myCol“
value="{{myCol}}">
</div>
<p>AngularJS resolves the expression and returns the result.</p>
<p>The background color of the input box will be whatever you write in the input
field.</p>
</body> </html>
Prepared by Prof. Martina D'souza , IT dept Refer Color.html file 31
AngularJS Objects
<!DOCTYPE html>
<html>
<script
src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.
min.js"></script>
<body>
<div ng-app="" ng-
init="person={firstName:'Sonoo',lastName:'Jaiswal'}">
<p>My name is {{ person.firstName }}</p>
</div>
</body>
</html>
Prepared by Prof. Martina D'souza , IT dept 32
AngularJS Expressions v/s JavaScript expressions:
• AngularJS expressions can be written inside HTML, while
JavaScript expressions cannot.
• AngularJS expressions support filters, while JavaScript expressions
do not.
• AngularJS expressions do not support conditionals, loops, and
exceptions, while JavaScript expressions do.
• Similarity between AngularJS Expressions and JavaScript
expressions:
• AngularJS expressions and JavaScript expressions both can contain
literals, operators and variables.
Prepared by Prof. Martina D'souza , IT dept 33
AngularJS Modules
An AngularJS module defines an application.
The module is a container for the different parts of an
application.
The module is a container for the application controllers.
Controllers always belong to a module.
Creating a Module
A module is created by using the AngularJS
function angular.module
<div ng-app="myApp">...</div>
<script>
var app = angular.module("myApp", []);
</script>
Prepared by Prof. Martina D'souza , IT dept 34
Adding a Controller
Add a controller in application, and refer to the controller with
the ng-controller directive:
<div ng-app="myApp" ng-controller="myCtrl">
{{ firstName + " " + lastName }}
</div>
<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.firstName = “Yash";
$scope.lastName = “Jain";
});
</script>
Prepared by Prof. Martina D'souza , IT dept 35
AngularJS - Controllers
• AngularJS application mainly relies on controllers to control the
flow of data in the application.
• A controller is defined using ng-controller directive.
• A controller is a regular JavaScript object that contains
attributes/properties, and functions.
• Each controller accepts $scope as a parameter, which refers to the
application/module that the controller needs to handle.
<div ng-app = "" ng-controller = "studentController">
...
</div>
Prepared by Prof. Martina D'souza , IT dept 36
<!DOCTYPE html>
<html>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.mi
n.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{firstName + " " + lastName}}
</div>
Prepared by Prof. Martina D'souza , IT dept 37
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
});
</script>
</body>
</html>
Prepared by Prof. Martina D'souza , IT dept 38
• The AngularJS application is defined by ng-app="myApp". The
application runs inside the <div>.
• The ng-controller="myCtrl" attribute is an AngularJS directive.
It defines a controller.
• The myCtrl function is a JavaScript function.
• AngularJS will invoke the controller with a $scope object.
• In AngularJS, $scope is the application object (the owner of
application variables and functions).
• The controller creates two properties (variables) in the scope
(firstName and lastName).
• The ng-model directives bind the input fields to the controller
properties (firstName and lastName).
Prepared by Prof. Martina D'souza , IT dept 39
Controller Methods
• A controller can also have methods (variables as functions):
<!DOCTYPE html>
<html>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angul
ar.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="personCtrl">
First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{fullName()}}</div>
Prepared by Prof. Martina D'souza , IT dept 40
<script>
var app = angular.module('myApp', []);
app.controller('personCtrl', function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
$scope.fullName = function() {
return $scope.firstName + " " + $scope.lastName;
};
});
</script>
</body>
</html>
Prepared by Prof. Martina D'souza , IT dept 41
Controllers In External Files
• In larger applications, it is common to store controllers in external
files.
• Just copy the code between the <script> tags into an external file
named personController.js:
<div ng-app="myApp" ng-controller="personCtrl">
First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{fullName()}}
</div>
<script src="personController.js"></script>
Prepared by Prof. Martina D'souza , IT dept 42
Custom directives
• In addition to all the built-in AngularJS directives, can create your
own 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, use a camel case
name, w3TestDirective,
• but when invoking it, use - separated name, w3-test-directive
Prepared by Prof. Martina D'souza , IT dept 43
Custom directives
• Custom directives are used in AngularJS to extend the
functionality of HTML.
• A custom directive simply replaces the element for which it is
activated.
• AngularJS application during bootstrap finds the matching
elements and do one time activity using its compile() method of
the custom directive then process the element using link()
method of the custom directive based on the scope of the
directive.
Prepared by Prof. Martina D'souza , IT dept 44
• AngularJS provides support to invoke a directive by using
following type of elements.
• Element directives − Directive activates when a matching
element is encountered.
• Attribute − Directive activates when a matching attribute is
encountered.
• CSS − Directive activates when a matching css style is
encountered.
• Comment − Directive activates when a matching comment is
encountered.
Prepared by Prof. Martina D'souza , IT dept 45
<!DOCTYPE html>
<html>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.
min.js"></script>
<body ng-app="myApp">
<w3-test-directive></w3-test-directive>
<script>
var app = angular.module("myApp", []);
app.directive("w3TestDirective", function() {
return {
template : "<h1>Made by a directive!</h1>"
};
}); Refer: customd.html
</script></body></html> Prepared by Prof. Martina D'souza , IT dept 46
<!DOCTYPE html>
<html>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.
min.js"></script>
<body ng-app="myApp">
<div w3-test-directive></div>
<script>
var app = angular.module("myApp", []);
app.directive("w3TestDirective", function() {
return {
template : "<h1>Made by a directive!</h1>"
};
});
</script></body></html> Prepared by Prof. Martina D'souza , IT dept 47
<!DOCTYPE html>
<html>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js
"></script>
<body ng-app="myApp">
<div class="w3-test-directive"></div>
<script>
var app = angular.module("myApp", []);
app.directive("w3TestDirective", function() {
return {
restrict : "C",
template : "<h1>Made by a directive!</h1>"
};
});
</script>
</body></html>
Prepared by Prof. Martina D'souza , IT dept 48
legal restrict values
• They are:
• E for Element name
• A for Attribute
• C for Class
• M for Comment
• By default the value is EA, meaning that both Element names
and attribute names can invoke the directive.
Prepared by Prof. Martina D'souza , IT dept 49
<!DOCTYPE html>
<html>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.mi
n.js"></script>
<body ng-app="myApp">
<!-- directive: w3-test-directive -->
<script>
var app = angular.module("myApp", []);
app.directive("w3TestDirective", function() {
return {
restrict : "M",
replace : true,
template : "<h1>Made by a directive!</h1>"
};
Prepared by Prof. Martina D'souza , IT dept 50
});</script></body></html>
<!DOCTYPE html>
<html>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.mi
n.js"></script>
<body ng-app="myApp">
<w3-test-directive></w3-test-directive>
<div w3-test-directive></div>
<script>
var app = angular.module("myApp", []);
app.directive("w3TestDirective", function() {
return {
restrict : "A",
template : "<h1>Made by a directive!</h1>"
}; Prepared by Prof. Martina D'souza , IT dept 51
AngularJS Data Binding
• Data binding is a very useful and powerful feature used in
software development technologies.
• It acts as a bridge between the view and business logic of the
application.
• Data binding in AngularJS is the synchronization between the
model and the view.
• AngularJS follows Two-Way data binding model.
• Software changes should be responsive, and changes within the
system should be catered to the changes in the user interface and
conversely, with precision and speed.
Prepared by Prof. Martina D'souza , IT dept 52
One-Way Data Binding
• The one-way data binding is an approach where a value is
taken from the data model and inserted into an HTML
element.
• There is no way to update model from view. It is used in
classical template systems. These systems bind data in only
one direction.
Prepared by Prof. Martina D'souza , IT dept 53
Two-Way Data Binding
• Data-binding in Angular apps is the automatic synchronization
of data between the model and view components.
• The view is a projection of the model at all times. If the model is
changed, the view reflects the change and vice versa.
Prepared by Prof. Martina D'souza , IT dept 54
<!DOCTYPE html>
<html>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script
>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
Name: <input ng-model="firstname">
<h1>{{firstname}}</h1>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.firstname = “Yash";
$scope.lastname = “Jain";
});
</script></body></html>
Prepared by Prof. Martina D'souza , IT dept 55
AngularJS - Filters
• Filters are exclusive to AngularJS and are not present in the
traditional JavaScript.
• The filters are used to modify output data to make them
compatible with different input data.
• The filters could be used in expressions or directives with the help
of the pipe operator. |
• These are the different kind of filters which are commonly
used:
Prepared by Prof. Martina D'souza , IT dept 56
Sr.No. Name & Description
1 uppercase
converts a text to upper case text.
2 lowercase
converts a text to lower case text.
3 currency
formats text in a currency format.
4 filter
filter the array to a subset of it based on provided criteria.
5 orderby
orders the array based on provided criteria.
Prepared by Prof. Martina D'souza , IT dept 57
Uppercase Filter
• Add uppercase filter to an expression using pipe character. Added
uppercase filter to print student name in all capital letters.
<body>
<div ng-app="myApp" ng-controller="personCtrl">
<p>The name is {{ lastName | uppercase }}</p>
</div>
<script>
angular.module('myApp', []);
app.controller('personCtrl', function($scope)
{
$scope.firstName = "John",
$scope.lastName = "Doe"
});
</script>
Prepared by Prof. Martina D'souza , IT dept 58
Currency Filter
• Add currency filter to an expression returning number using pipe
character.
• Added currency filter to print fees using currency format.
<body>
<div ng-app="myApp" ng-controller="costCtrl">
<h1>Price: {{ price | currency }}</h1>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('costCtrl', function($scope) {
$scope.price = 58;
});
</script> Prepared by Prof. Martina D'souza , IT dept 59
Filter
To display only required subjects, we use subjectName as filter.
<body>
<div ng-app="myApp" ng-controller="namesCtrl">
<ul>
<li ng-repeat="x in names | filter : 'i'">
{{ x }}
</li>
</ul>
</div>
Prepared by Prof. Martina D'souza , IT dept 60
<script>
angular.module('myApp', []).controller('namesCtrl', function($scope) {
$scope.names = [
'Jani',
'Carl',
'Margareth',
'Hege',
'Joe',
'Gustav',
'Birgit',
'Mary',
'Kai'
];
});
</script>
<p>This example displays only the names containing the letter "i".</p>
</body>
Prepared by Prof. Martina D'souza , IT dept 61
AngularJS - Scopes
• Scope is a special JavaScript object that connects controller with
views.
• Scope contains model data.
• In controllers, model data is accessed via $scope object.
• The $scope is passed as first argument to controller during its
constructor definition.
• The $scope.message and $scope.type are the models which are
used in the HTML page.
Prepared by Prof. Martina D'souza , IT dept 62
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<h1>{{carname}}</h1>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.carname = "Volvo";
});
</script>
</body>
Prepared by Prof. Martina D'souza , IT dept 63
Note
• If we consider an AngularJS application to consist of:
• View, which is the HTML.
• Model, which is the data available for the current view.
• Controller, which is the JavaScript function that
makes/changes/removes/controls the data.
• Then the scope is the Model.
• The scope is a JavaScript object with properties and methods,
which are available for both the view and the controller.
Prepared by Prof. Martina D'souza , IT dept 64
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<input ng-model="name">
<h1>My name is {{name}}</h1>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.name = "John Doe";
});
</script>
</body>
</html>
Prepared by Prof. Martina D'souza , IT dept 65
AngularJS - Dependency Injection
• AngularJS Dependency injection defines, how the various
components of the software are dependent on each other.
• Instead of hard-coding a component within another component, a
component is given their own dependencies using dependency
injection.
• Why Dependency Injection?
• AngularJS Dependency injections make an application modularize.
• AngularJS DI makes easier to reuse components of an application.
• It makes easier to test components of an application.
• It makes easier to configure components of an application.
Prepared by Prof. Martina D'souza , IT dept 70
• Core components that can be injected as a dependency in
one another:
• Value
• Factory
• Service
• Provider
• Constant
Prepared by Prof. Martina D'souza , IT dept 71
Value
• Value is an object. It can be a number, string or javascript object.
• It is used to pass the value to controller, service or factories in
config or run phase.
• (config phase is when AngularJS bootstraps itself).
//define a module
var mainApp = angular.module("mainApp", []);
//create a value object as "defaultInput" and pass it a data.
mainApp.value("defaultInput", 5);
Prepared by Prof. Martina D'souza , IT dept 72
//inject the value in the controller using its name "defaultInput"
mainApp.controller('CalcController', function($scope,
CalcService, defaultInput) {
$scope.number = defaultInput;
$scope.result = CalcService.square($scope.number);
$scope.square = function() {
$scope.result = CalcService.square($scope.number);
}
});
Prepared by Prof. Martina D'souza , IT dept 73
Factory
• Factory is a function which is used to return value.
• It creates a value on demand whenever a service or a controller
requires it.
• It generally uses a factory function to calculate and return the
value.
• //define a module
• var mainApp = angular.module("mainApp", []);
Prepared by Prof. Martina D'souza , IT dept 74
• //create a factory "MathService" which provides a method
multiply to return multiplication of two numbers
• mainApp.factory('MathService', function() {
• var factory = {};
• factory.multiply = function(a, b) {
• return a * b
• }
• return factory;
• });
Prepared by Prof. Martina D'souza , IT dept 75
• //inject the factory "MathService" in a service to utilize the
multiply method of factory.
• mainApp.service('CalcService', function(MathService) {
• this.square = function(a) {
• return MathService.multiply(a,a);
• }
• });
Prepared by Prof. Martina D'souza , IT dept 76
Service
• Service is a singleton JavaScript object containing a set of
functions to perform certain tasks.
• Service is defined using service() function and it is then injected
into the controllers.
//define a module
var mainApp = angular.module("mainApp", []);
//create a service which defines a method square to return square of
a number.
mainApp.service('CalcService', function(MathService) {
this.square = function(a) {
return MathService.multiply(a,a);
}});
Prepared by Prof. Martina D'souza , IT dept 77
//inject the service "CalcService" into the controller
mainApp.controller('CalcController', function($scope, CalcService,
defaultInput) {
$scope.number = defaultInput;
$scope.result = CalcService.square($scope.number);
$scope.square = function() {
$scope.result = CalcService.square($scope.number);
}
});
Prepared by Prof. Martina D'souza , IT dept 78
Provider
• Provider is used by AngularJS internally to create 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.
//define a module
var mainApp = angular.module("mainApp", []);
...
Prepared by Prof. Martina D'souza , IT dept 79
//create a service using provider which defines a method square to
return square of a number.
mainApp.config(function($provide) {
$provide.provider('MathService', function() {
this.$get = function() {
var factory = {};
factory.multiply = function(a, b) {
return a * b;
}
return factory;
};
});
});
Prepared by Prof. Martina D'souza , IT dept 80
Constant
• Constants are used to pass values at the config phase considering
the fact that value cannot be used during the config phase.
• mainApp.constant("configParam", "constant value");
Prepared by Prof. Martina D'souza , IT dept 81
Note
• AngularJS Dependency injection is the process of injecting
dependent functionality at run time into modules.
• It helps in achieving reusability of code.
• Suppose you have a functionality that can use at multiple places in
a single application so better to define a central service for it and
then inject into different modules of an application as a
dependency.
Prepared by Prof. Martina D'souza , IT dept 82
AngularJS - Services
• AngularJS services are JavaScript functions for specific tasks,
which can be reused throughout the application.
• AngularJS built-in services starts with $, same as other built-in
objects.
• AngularJS includes services for different purposes.
• For example, $http service can be used to send an AJAX request to
the remote server.
• AngularJS also allows you to create custom service for your
application.
• Most AngularJS services interact with the controller, model or
custom directives.
• However, some services interact with view (UI) also for UI
specific tasks.
Prepared by Prof. Martina D'souza , IT dept 83
In AngularJS you can make your own service, or use
one of the many built-in services.
Prepared by Prof. Martina D'souza , IT dept 84
Built in Angularjs Services
AngularJS framework instantiates a service when
an application component depends on it. Also, all
the components share the same instance of a85
Prepared by Prof. Martina D'souza , IT dept
• AngularJS provides many inbuilt services.
• For example, $http, $route, $window, $location, etc.
• Each service is responsible for a specific task such as
• the $http is used to make ajax call to get the server data,
• the $route is used to define the routing information, and so on.
Prepared by Prof. Martina D'souza , IT dept 86
$http Service
• The $http service is used to send or receive data from the remote
server using browser's XMLHttpRequest .
• $http is a service as an object.
• It includes following shortcut methods.
Prepared by Prof. Martina D'souza , IT dept 87
$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.
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$http.get("welcome.htm").then(function (response) {
$scope.myWelcome = response.data;
});
});
</script>
Prepared by Prof. Martina D'souza , IT dept 88
$timeout Service
• The $timeout service is AngularJS' version of
the window.setTimeout function.
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $timeout) {
$scope.myHeader = "Hello World!";
$timeout(function () {
$scope.myHeader = "How are you today?";
}, 2000);
});
</script>
Prepared by Prof. Martina D'souza , IT dept 89
$location service
• The $location service has methods which return information
about the location of the current web page
Prepared by Prof. Martina D'souza , IT dept 90
Eg
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<p>The url of this page is:</p>
<h3>{{myUrl}}</h3>
</div>
<p>This example uses the built-in $location service to get the
absolute url of the page.</p>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $location) {
$scope.myUrl = $location.absUrl();
});
</script>
Prepared by Prof. Martina D'souza , IT dept 91
$log Service
• AngularJs includes logging service $log, which logs the messages
to the browser's console.
• The $log service includes different methods to log the error,
information, warning or debug information.
• It can be useful in debugging and auditing.
Prepared by Prof. Martina D'souza , IT dept 92
<body ng-app="myApp" >
<div ng-controller="myController">
<p>Please check the browser console for the logging
information.</p>
</div>
<script>
var myApp = angular.module('myApp', []);
myApp.controller("myController", function ($log)
$log.log('This is log.');
$log.error('This is error.');
$log.info('This is info.');
$log.warn('This is warning.');
$log.debug('This is debugging.');
}); </script></body>
Prepared by Prof. Martina D'souza , IT dept 93
$interval Service
• AngularJS includes $interval service which performs the same
task as setInterval() method in JavaScript.
• The $interval is a wrapper for setInterval() method, so that it will
be easy to override, remove or mocked for testing.
• The $interval service executes the specified function on every
specified milliseconds duration.
Prepared by Prof. Martina D'souza , IT dept 94
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<p>The time is:</p>
<h1>{{theTime}}</h1>
</div>
<p>The $interval service runs a function every specified
millisecond.</p>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $interval) {
$scope.theTime = new Date().toLocaleTimeString();
$interval(function () {
$scope.theTime = new Date().toLocaleTimeString();
}, 1000);
});</script> Prepared by Prof. Martina D'souza , IT dept 95
$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.
Prepared by Prof. Martina D'souza , IT dept 96
<body ng-app="myApp" ng-controller="myController">
<button ng-click="DisplayAlert('Hello World!')">Display Alert</button>
<button ng-click="DisplayPrompt()">Display Prompt</button>
<script>
var myApp = angular.module('myApp', []);
myApp.controller("myController", function ($scope, $window) {
$scope.DisplayAlert = function (message) {
$window.alert(message);
}
Prepared by Prof. Martina D'souza , IT dept 97
$scope.DisplayPrompt = function () {
var name = $window.prompt('Enter Your Name');
$window.alert('Hello ' + name);
}
});
</script>
Prepared by Prof. Martina D'souza , IT dept 98
Events
AngularJS provides multiple events associated with the HTML
controls.
For example, ng-click directive is generally associated with a
button.
ng-click
ng-dbl-click
ng-mousedown
ng-mouseup
ng-mouseenter
ng-mouseleave
ng-mousemove
ng-mouseover
ng-keydown
ng-keyup Prepared by Prof. Martina D'souza , IT dept 99
Mouse events
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<h1 ng-mousemove="count = count + 1">Mouse Over
Me!</h1>
<h2>{{ count }}</h2>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.count = 0;
});
</script>
Prepared by Prof. Martina D'souza , IT dept 100
</body>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<button ng-click="count = count + 1">Click Me!</button>
<p>{{ count }}</p>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.count = 0;
});</script>
Prepared by Prof. Martina D'souza , IT dept 101
$event Object
Can also pass the $event object as an argument when calling the
function.
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<h1 ng-mousemove="myFunc($event)">Mouse Over Me!</h1>
<p>Coordinates: {{x + ', ' + y}}</p>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.myFunc = function(myE) {
$scope.x = myE.clientX;
$scope.y = myE.clientY;
}
Prepared by Prof. Martina D'souza , IT dept 102
});</script>
AngularJS - Forms
• The HTML form is a collection
of input controls where user can
enter the data.
• Forms in AngularJS provides
data-binding and validation of
input controls.
• Student Information form with
submit and reset functionality.
Prepared by Prof. Martina D'souza , IT dept 103
• Data-Binding
• Input controls provides data-binding by using the ng-
model directive.
• <input type="text" ng-model="firstname">
• The application does now have a property named firstname.
• The ng-model directive binds the input controller to the rest of your
application.
<script>
var app = angular.module('myApp', []);
app.controller('formCtrl', function($scope) {
$scope.firstname = "John";
});
</script>
Prepared by Prof. Martina D'souza , IT dept 104
• Checkbox
• A checkbox has the value true or false. Apply the ng-
model directive to a checkbox, and use its value in your
application.
<form>
Check to show a header:
<input type="checkbox" ng-model="myVar">
</form>
<h1 ng-show="myVar">My Header</h1>
Prepared by Prof. Martina D'souza , IT dept 105
• Radiobuttons
• Bind radio buttons to application with the ng-model directive.
• Radio buttons with the same ng-model can have different
values, but only the selected one will be used.
<form>
Pick a topic:
<input type="radio" ng-model="myVar" value="dogs">Dogs
<input type="radio" ng-model="myVar" value="tuts">Tutorials
<input type="radio" ng-model="myVar" value="cars">Cars
</form>
Prepared by Prof. Martina D'souza , IT dept 106
• Selectbox
• Bind select boxes to your application with the ng-model directive.
• The property defined in the ng-model attribute will have the value
of the selected option in the selectbox.
<form>
Select a topic:
<select ng-model="myVar">
<option value="">
<option value="dogs">Dogs
<option value="tuts">Tutorials
<option value="cars">Cars
</select>
</form>
Prepared by Prof. Martina D'souza , IT dept 107
<!DOCTYPE html>
<html ng-app="studentApp">
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.16/angular.
min.js"></script>
</head>
<body ng-controller="studentController">
<h1>Student Information:</h1>
<form ng-submit="submitStudnetForm()" >
First Name: <br />
<input type="text" id="firstName" ng-
model="student.firstName" /> <br />
Prepared by Prof. Martina D'souza , IT dept 108
Last Name:<br />
<input type="text" id="lastName" ng-
model="student.lastName" /> <br />
<label for="dob" >DoB</label><br />
<input type="date" id="dob" ng-model="student.DoB" /> <br
/><br />
<label for="gender" >Gender</label> <br />
<select id="gender" ng-model="student.gender">
<option value="male">Male</option>
<option value="female">Female</option>
</select><br /> <br />
Prepared by Prof. Martina D'souza , IT dept 109
<span>Training Type:</span><br />
<label><input value="online" type="radio"
name="training" ng-model="student.trainingType"
/>Online</label><br />
<label><input value="onsite" type="radio"
name="training" ng-model="student.trainingType" />OnSite</label>
<br /><br />
<span>Subjects</span><br />
<label><input type="checkbox" ng-model="student.maths"
/>Maths</label> <br />
<label><input type="checkbox" ng-
model="student.physics" />Physics</label> <br />
<label><input type="checkbox" ng-
model="student.chemistry" />Chemistry</label><br /><br />
Prepared by Prof. Martina D'souza , IT dept 110
<input type="submit" value="Submit" />
<input type="reset" ng-click="resetForm()" value="Reset" /> <br
/>
</form>
<script>
//1. create app module
var studentApp = angular.module('studentApp', []);
//2. create controller
studentApp.controller("studentController", function ($scope,
$http) {
Prepared by Prof. Martina D'souza , IT dept 111
//3. attach originalStudent model object
$scope.originalStudent = {
firstName: 'James',
lastName: 'Bond',
DoB: new Date('01/31/1980'),
gender: 'male',
trainingType: 'online',
maths: false,
physics: true,
chemistry: true
};
Prepared by Prof. Martina D'souza , IT dept 112
//4. copy originalStudent to student. student will be bind to a form
$scope.student = angular.copy($scope.originalStudent);
//5. create submitStudentForm() function. This will be called
when user submits the form
$scope.submitStudnetForm = function () {
// send $http request to save student
};
//6. create resetForm() function. This will be called on Reset
button click.
$scope.resetForm = function () {
Prepared by Prof. Martina D'souza , IT dept 113
$scope.student = angular.copy($scope.OriginalStudent);
};
});
</script>
</body>
</html>
Prepared by Prof. Martina D'souza , IT dept 114
Validation in AngularJS
• Implement client side validation in AngularJS form.
• AngularJS includes the following validation directives.
Prepared by Prof. Martina D'souza , IT dept 115
<form name="myForm">
<input name="myInput" ng-model="myInput" required>
</form>
<p>The input's valid state is:</p>
<h1>{{myForm.myInput.$valid}}</h1>
Prepared by Prof. Martina D'souza , IT dept 116
email
• <form name="myForm">
• <input name="myInput" ng-model="myInput" type="email">
</form>
<p>The input's valid state is:</p>
<h1>{{myForm.myInput.$valid}}</h1>
Prepared by Prof. Martina D'souza , IT dept 117
Form State and Input State
• AngularJS is constantly updating the state of both the form and the
input fields.
• Input fields have the following states:
• $untouched -The field has not been touched yet
• $touched -The field has been touched
• $pristine -The field has not been modified yet
• $dirty -The field has been modified
• $invalid -The field content is not valid
• $valid -The field content is valid
• They are all properties of the input field, and are either true or false.
Prepared by Prof. Martina D'souza , IT dept 118
• Forms have the following states:
• $pristine -No fields have been modified yet
• $dirty- One or more have been modified
• $invalid -The form content is not valid
• $valid -The form content is valid
• $submitted -The form is submitted
• They are all properties of the form, and are either true or false.
Prepared by Prof. Martina D'souza , IT dept 119
<body ng-app="">
<form name="form1">
<p>Name:
<input name="username" ng-model="username" required>
<span ng-show="form1.username.$pristine &&
form1.username.$invalid">
The name is required.</span>
</p>
Prepared by Prof. Martina D'souza , IT dept 120
<p>Address:
<input name="useraddress" ng-model="useraddress" required>
</p>
</form>
<p>We use the ng-show directive to only
show the error message if the field has
not modified yet AND content present in
the field is invalid.</p>
</body>
</html>
Prepared by Prof. Martina D'souza , IT dept 121
<div ng-app="">
<form name="personForm">
First Name: <input type="text" name="firstname" ng-
model="person.fname" required />
<span ng-show="personForm.firstname.$touched &&
personForm.firstname.$invalid
"> Required! </span><br /><br />
Last Name:<input type="text" name="lastname" ng-
model="person.lname" required />
<span ng-show="personForm.lastname.$dirty &&
personForm.lastname.$valid"> Thanks for Text </span><br /><br />
</form>
</div>
Prepared by Prof. Martina D'souza , IT dept 122
CSS Classes
• AngularJS adds CSS classes to forms and input fields depending on
their states.
• The following classes are added to, or removed from, input fields:
• ng-untouched- The field has not been touched yet
• ng-touched- The field has been touched
• ng-pristine -The field has not been modified yet
• ng-dirty -The field has been modified
• ng-valid -The field content is valid
• ng-invalid -The field content is not valid
• ng-valid-key One key for each validation. Example: ng-valid-
required, useful when there are more than one thing that must be
validated
• ng-invalid-key Example: ng-invalid-required
Prepared by Prof. Martina D'souza , IT dept 123
• The following classes are added to, or removed from, forms:
• ng-pristine -No fields has not been modified yet
• ng-dirty- One or more fields has been modified
• ng-valid -The form content is valid
• ng-invalid -The form content is not valid
• ng-valid-key One key for each validation. Example: ng-valid-
required, useful when there are more than one thing that must be
validated
• ng-invalid-key Example: ng-invalid-required
• The classes are removed if the value they represent is false.
Prepared by Prof. Martina D'souza , IT dept 124
CSS example
<head><title>AngularJs Applying classes for Form Validation
</title>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angula
r.min.js"></script>
<style>
form.ng-invalid {
background-color:#f2672e;
}
form.ng-valid {
background-color:#2b8bc0;
}
</style></head>
Prepared by Prof. Martina D'souza , IT dept 125
<body>
<div ng-app="">
<form name="personForm">
<br />
First Name:<input type="text" name="firstname" ng-
model="person.fname" required /><br /><br />
Last Name:<input type="text" name="lastname" ng-
model="person.lname" required />
<br /><br />
</form>
</div></body>
Prepared by Prof. Martina D'souza , IT dept 126
Routing
• 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.
Prepared by Prof. Martina D'souza , IT dept 127
ngRoute
• 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.
Prepared by Prof. Martina D'souza , IT dept 128
Google CDN
• You can also use the CDN in your application to include this file.
• https://ajax.googleapis.com/ajax/libs/angularjs/1.2.28//angular-
route.min.js
• If you are bundling this file into your application, then you can add
it to your page with below code.
• <script src="angular-route.js">
Prepared by Prof. Martina D'souza , IT dept 129
• 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.
• three different ways to include the ng-view directive
<div ng-view></div>
<ng-view></ng-view>
<div class="ng-view"></div>
Prepared by Prof. Martina D'souza , IT dept 130
$routeProvider
• $routeProvider is used to configure the routes.
• With the $routeProvider you can define what page to display
when a user clicks a link.
• Use 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.
Prepared by Prof. Martina D'souza , IT dept 131
AngularJS Routing Syntax
• The following syntax is used to configure the routes in AngularJS.
var app = angular.module("appName", ['ngRoute']);
app.config(function($routeProvider) {
$routeProvider
.when('/view1', {
templateUrl: 'view1.html',
controller: 'FirstController'
})
Prepared by Prof. Martina D'souza , IT dept 132
.when('/view2', {
templateUrl: 'view2.html',
controller: 'SecondController'
})
.otherwise({
redirectTo: '/view1'
});
});
when() method takes a path and a route as parameters.
path is a part of the URL after the # symbol.
route contains two properties – templateUrl and controller.
Prepared by Prof. Martina D'souza , IT dept 133
• templateUrl property defines which HTML template AngularJS
should load and display inside the div with the ngView directive.
• controller property defines which controllers should be used
with the HTML template.
• When the application is loaded, path is matched against the part
of the URL after the # symbol.
• If no route paths matches the given URL the browser will be
redirected to the path specified in the otherwise() function.
Prepared by Prof. Martina D'souza , IT dept 134
<!DOCTYPE html>
<html>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.mi
n.js"></script>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular-
route.js"></script>
<body ng-app="myApp">
<p><a href="#/!">Main</a></p>
<a href="#!red">Red</a>
<a href="#!green">Green</a>
<a href="#!blue">Blue</a>
Prepared by Prof. Martina D'souza , IT dept 135
<div ng-view></div>
<script>
var app = angular.module("myApp", ["ngRoute"]);
app.config(function($routeProvider) {
$routeProvider
.when("/", { .when("/green", {
templateUrl : "main.htm" templateUrl : "green.htm"
})
})
.when("/blue", {
.when("/red", { templateUrl : "blue.htm"
templateUrl : "red.htm" });
}) });
</script>
<p>Click on the links to navigate to
"red.htm", "green.htm", "blue.htm",
Prepared by Prof. Martina D'souza , IT dept 136
or back to
• With the $routeProvider you can also define a controller for each
"view".
<!DOCTYPE html>
<html>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angula
r.min.js"></script>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angula
r-route.js"></script>
<body ng-app="myApp">
Prepared by Prof. Martina D'souza , IT dept 137
<p><a href="#/!">Main</a></p>
<a href="#!london">City 1</a>
<a href="#!paris">City 2</a>
<p>Click on the links.</p>
<p>Note that each "view" has its own controller which each gives
the "msg" variable a value.</p>
<div ng-view></div>
<script>
Prepared by Prof. Martina D'souza , IT dept 138
var app = angular.module("myApp", ["ngRoute"]);
app.config(function($routeProvider) {
$routeProvider
.when("/", { app.controller("londonCtrl
templateUrl : "main.htm", ", function ($scope) {
}) $scope.msg = "I love
.when("/london", { London";
templateUrl : "london.htm",});
controller : "londonCtrl"
app.controller("parisCtrl",
})
function ($scope) {
.when("/paris", {
templateUrl : "paris.htm",
$scope.msg = "I love
controller : "parisCtrl" Paris";
}); });
}); </script></body></html>
Prepared by Prof. Martina D'souza , IT dept 139
• london.htm
• <h1>London</h1>
<h3>London is the capital city of England.</h3>
<p>It is the most populous city in the United Kingdom, with a
metropolitan area of over 13 million inhabitants.</p>
<p>{{msg}}</p>
• paris.htm
• <h1>Paris</h1>
<h3>Paris is the capital city of France.</h3>
<p>The Paris area is one of the largest population centers in
Europe, with more than 12 million inhabitants.</p>
<p>{{msg}}</p>
Prepared by Prof. Martina D'souza , IT dept 140
Template
• We have used the templateUrl property in
the $routeProvider.when method.
• Can also use the template property, which allows to write HTML
directly in the property value, and not refer to a page.
var app = angular.module("myApp", ["ngRoute"]);
app.config(function($routeProvider) {
$routeProvider
Prepared by Prof. Martina D'souza , IT dept 141
.when("/", {
template : "<h1>Main</h1><p>Click on the links to change this
content</p>"
})
.when("/banana", {
template : "<h1>Banana</h1><p>Bananas contain around 75%
water.</p>"
})
.when("/tomato", {
template : "<h1>Tomato</h1><p>Tomatoes contain around 95%
water.</p>"
});
});
Prepared by Prof. Martina D'souza , IT dept 142
The otherwise method
• You can also use the otherwise method, which is the default route
when none of the others get a match.
• .when("/tomato", {
template : "<h1>Tomato</h1><p>Tomatoes contain around 95%
water.</p>"
})
.otherwise({
template : "<h1>None</h1><p>Nothing has been selected</p>"
});
});
Prepared by Prof. Martina D'souza , IT dept 143
Built-in Helper Functions
• angular.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)
• If the objects or values pass the === comparison
• If both objects or values are of the same type, and all of their
properties are also equal by using angular.equals
• Both values are equal to NaN
• Both values represent the same regular expression's result.
Prepared by Prof. Martina D'souza , IT dept 144
• angular.equals(1, 1) // true
• angular.equals(1, 2) // false
• angular.equals({}, {}) // true, note that {}==={} is false
• angular.equals({a: 1}, {a: 1}) // true
• angular.equals({a: 1}, {a: 2}) // false
• angular.equals(NaN, NaN) // true
Prepared by Prof. Martina D'souza , IT dept 145
angular.isString
• The function angular.isString returns true if the object or value
given to it is of the type string
• angular.isString(value1)
• Examples
• angular.isString("hello") // true
• angular.isString([1, 2]) // false
• angular.isString(42) // false
Prepared by Prof. Martina D'souza , IT dept 146
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)
• Examples
• angular.isArray([]) // true
• angular.isArray([2, 3]) // true
• angular.isArray({}) // false
• angular.isArray(17) // false
Prepared by Prof. Martina D'souza , IT dept 147
angular.merge
• The function angular.merge takes all the enumerable properties
from the source object to deeply extend the destination object.
• The function returns a reference to the now extended destination
object
• angular.merge(destination, source)
• Examples
• angular.merge({}, {}) // {}
• angular.merge({name: "king roland"}, {password: "12345"})
• // {name: "king roland", password: "12345"}
• angular.merge({a: 1}, [4, 5, 6]) // {0: 4, 1: 5, 2: 6, a: 1}
• angular.merge({a: 1}, {b: {c: {d: 2}}}) //
{"a":1,"b":{"c":{"d":2}}}
Prepared by Prof. Martina D'souza , IT dept 148
angular.copy
• The angular.copy function takes an object, array or a value and
creates a deep copy of it.
• angular.copy()
• Example:
• Objects:
• let obj = {name: "vespa", occupation: "princess"};
• let cpy = angular.copy(obj);
• cpy.name = "yogurt"
• // obj = {name: "vespa", occupation: "princess"}
• // cpy = {name: "yogurt", occupation: "princess"}
Prepared by Prof. Martina D'souza , IT dept 149
All the Best
Prepared by Prof. Martina D'souza , IT dept 150