0% found this document useful (0 votes)
131 views62 pages

Unit V

AngularJS is an open-source JavaScript framework for building dynamic web applications and sites. It extends HTML with new attributes and binds data to HTML elements through expressions and directives. AngularJS allows developers to write client-side applications in a clean MVC-like way. Some key features include data binding, reusable components, dependency injection, and generating dynamic views from data sources. The document then discusses downloading AngularJS, provides an example "Hello World" application, and describes some important built-in directives like ng-app, ng-model, and ng-repeat.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
131 views62 pages

Unit V

AngularJS is an open-source JavaScript framework for building dynamic web applications and sites. It extends HTML with new attributes and binds data to HTML elements through expressions and directives. AngularJS allows developers to write client-side applications in a clean MVC-like way. Some key features include data binding, reusable components, dependency injection, and generating dynamic views from data sources. The document then discusses downloading AngularJS, provides an example "Hello World" application, and describes some important built-in directives like ng-app, ng-model, and ng-repeat.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 62

Advanced Java Script-JQuery/AJAX/JSON/Angular JS UNIT IV

UNIT-V
Introduction To AngularJS
1. What is AngularJS? Explain the need of AngularJS in real web sites?
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. Its latest version is 1.4.3. AngularJS is a structural framework
for dynamic web apps. It lets you use HTML as your template language and lets you
extend HTML's syntax to express your application's components clearly and
succinctly. 
Features
 AngularJS is a powerful JavaScript based development framework to create
RICH Internet Application(RIA).
 AngularJS provides developers options to write client side application (using
JavaScript) in a clean MVC(Model View Controller) way.
 Application written in AngularJS is 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.
Overall, AngularJS is a framework to build large scale and high performance web
application while keeping them as easy-to-maintain.
Concepts
Following diagram depicts some important parts of AngularJS
Advanced Java Script-JQuery/AJAX/JSON/Angular JS UNIT IV

Advantages of AngularJS
 AngularJS provides capability to create Single Page Application in a very
clean and maintainable way.
 AngularJS provides data binding capability to HTML thus 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, developer write less code and get more functionality.
 In AngularJS, views are pure html pages, and controllers written in JavaScript
do the business processing.
On top of everything, AngularJS applications can run on all major browsers and
smart phones including Android and iOS based phones/tablets.
Disadvantages of AngularJS
Though AngularJS comes with lots of plus points but same time we should consider
the following points −
 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 your application user disables JavaScript then user will just
see the basic page and nothing more.
The AngularJS Components
The AngularJS framework can be divided into following 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.
2. Explain the process for downloading AngularJS?
AngularJS : Downloading AngularJS and Setting up
Downloading and Installing AngularJS is extremely easy and takes no time or
money.Its open source and hence available free from their website angularjs.org
Create a new folder to store the AngularJS JavaScript Files, and use
the <script> element to link the files on the document.
Advanced Java Script-JQuery/AJAX/JSON/Angular JS UNIT IV

You can also serve AngularJS files using a Content Distribution Newtwork (CDN) ,
instead of having the files on the local server.
AngularJS : Installing AngularJS using CDN
To use the Content Distribution Network(CDN) you simply need to put the
following script in the <head> element
The latest stable version at the time of writing this is version 1.3x(stable)
The advantage of using Content Delivery Networks is that they provide good speed
and performance, and are bandwidth friendly. AngularJS files are hosted for free on
large Web Organisations like Google, Microsoft , Yahoo etc.
Syntax: AngularJS files Hosted on Google CDN
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
</script>
AngularJS : Installing AngularJS on your Server
Go to the website angularjs.org and click on Download button which appears right
in the front page.Click on that you will see a Dialog Box like below.

To choose a minified version, select 1.3.x(legacy) for the branch option and


the Minified for the build option.
When the Download is completed move the .js files into the angularJS folder
There you go, you have downloaded and installed.
Advanced Java Script-JQuery/AJAX/JSON/Angular JS UNIT IV

AngularJS : Browser Support


AngularJS has support on all Major Web browser
like Safari , Chrome , FireFox and Opera etc.
If possible try using Google Chrome which comes from the parent company
of AngularJS. The reason being that chrome is a well built browser and conforms to
latest stable W3C standards, and great developer support using Key F12
Google Chrome also provides an extension providing support for AngularJS to
the F12 tools, its called as Batarang AngularJS, though not a perfect tool but surely
useable.
3. AngularJS first example
Before we start with creating actual HelloWorld application using AngularJS, let us
see what are the actual parts of a AngularJS 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.
Steps to create AngularJS Application
Step 1 − Load framework
Being a pure JavaScript framework, It can be added using <Script> tag.
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
</script>
Step 2 − Define AngularJS Application using ng-app directive
<div ng-app = "">
...
</div>
Step 3 − Define a model name using ng-model directive
<p>Enter your Name: <input type = "text" ng-model = "name"></p>
Step 4 − Bind the value of above model defined using ng-bind directive.
<p>Hello <span ng-bind = "name"></span>!</p>
Steps to run AngularJS Application
Use above mentioned three steps in an HTML page.
testAngularJS.htm
Advanced Java Script-JQuery/AJAX/JSON/Angular JS UNIT IV

<html>
<head>
<title>AngularJS First Application</title>
</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>
<script src =
"https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
</body>
</html>
Output
Open textAngularJS.htm in a web browser. Enter your name and see the result.
Sample Application

Enter your Name: 


Hello !
How AngularJS integrates with HTML
 ng-app directive indicates the start of AngularJS application.
 ng-model directive then creates a model variable named "name" which can be
used with the html page and within the div having ng-app directive.
 ng-bind then uses the name model to be displayed in the html span tag
whenever user input something in the text box.
 Closing</div> tag indicates the end of AngularJS application.
4. Write about AngularJS built-in directives?

AngularJS directives are used to extend HTML. These are special attributes starting
with ng- prefix. We're going to discuss following directives −
 ng-app − This directive starts an AngularJS Application.
 ng-init − This directive initializes application data.
 ng-model − This directive binds the values of AngularJS application data to
HTML input controls.
Advanced Java Script-JQuery/AJAX/JSON/Angular JS UNIT IV

 ng-repeat − This directive repeats html elements for each item in a collection.
ng-app directive
ng-app directive starts an AngularJS Application. It defines the root element. It
automatically initializes or bootstraps the application when web page containing
AngularJS Application is loaded. It is also used to load various AngularJS modules
in AngularJS Application. In following example, we've defined a default AngularJS
application using ng-app attribute of a div element.
<div ng-app = "">
...
</div>
ng-init directive
ng-init directive initializes an AngularJS Application data. It is used to put values to
the variables to be used in the application. In following example, we'll initialize an
array of countries. We're using JSON syntax to define 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>
ng-model directive
This directive binds the values of AngularJS application data to HTML input
controls. In following example, we've defined a model named "name".
<div ng-app = "">
...
<p>Enter your Name: <input type = "text" ng-model = "name"></p>
</div>
ng-repeat directive
ng-repeat directive repeats html elements for each item in a collection. In following
example, we've iterated over array of countries.
<div ng-app = "">
...
<p>List of Countries with locale:</p>
<ol>
<li ng-repeat = "country in countries">
Advanced Java Script-JQuery/AJAX/JSON/Angular JS UNIT IV

{{ 'Country: ' + country.name + ', Locale: ' + country.locale }}


</li>
</ol>
</div>
Example
Following example will showcase all the above mentioned directives.
testAngularJS.htm
<html>

<head>

<title>AngularJS Directives</title>

</head>

<body>

<h1>Sample Application</h1>

<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>

<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></


script>

</body>
Advanced Java Script-JQuery/AJAX/JSON/Angular JS UNIT IV

</html>
Output
Open textAngularJS.htm in a web browser. Enter your name and see the result.
5. Write about AngularJS expressions?
Expressions are used to bind application data to html. Expressions are written inside
double braces like {{ expression}}. Expressions behaves in same way as ng-bind
directives. AngularJS application expressions are pure javascript expressions and
outputs the data where they are used.
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>
Example
Following example will showcase all the above mentioned expressions.
testAngularJS.htm
<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>
Advanced Java Script-JQuery/AJAX/JSON/Angular JS UNIT IV

</div>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></
script>
</body>
</html>
Output
Open textAngularJS.htm in a web browser. See the result.
6. Write about AngularJS modules?
AngularJS supports modular approach. Modules are used to separate logics say
services, controllers, application etc. and keep the code clean. We define modules in
separate js files and name them as per the module.js file. In this example we're going
to create two modules.
Application Module − used to initialize an application with controller(s).
Controller Module − used to define the controller.
Application Module
mainApp.js
var mainApp = angular.module("mainApp", []);
Here we've declared an application mainApp module using angular.module function.
We've passed an empty array to it. This array generally contains dependent modules.
Controller Module
studentController.js
mainApp.controller("studentController", function($scope) {
$scope.student = {
firstName: "Mahesh",
lastName: "Parashar",
fees:500,
subjects:[
{name:'Physics',marks:70},
{name:'Chemistry',marks:80},
{name:'Math',marks:65},
{name:'English',marks:75},
{name:'Hindi',marks:67}
],
Advanced Java Script-JQuery/AJAX/JSON/Angular JS UNIT IV

fullName: function() {
var studentObject;
studentObject = $scope.student;
return studentObject.firstName + " " + studentObject.lastName;
}
};
});
Here we've declared a controller studentController module using mainApp.controller
function.
Use Modules
<div ng-app = "mainApp" ng-controller = "studentController">
...
<script src = "mainApp.js"></script>
<script src = "studentController.js"></script>
</div>
Here we've used application module using ng-app directive and controller using ng-
controller directive. We've imported mainApp.js and studentController.js in the main
html page.
Example
Following example will showcase all the above mentioned modules.
testAngularJS.htm
<html>
<head>
<title>Angular JS Modules</title>
<script src =
"https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src = "/angularjs/src/module/mainApp.js"></script>
<script src = "/angularjs/src/module/studentController.js"></script>
<style>
table, th , td {
border: 1px solid grey;
border-collapse: collapse;
padding: 5px;
}
Advanced Java Script-JQuery/AJAX/JSON/Angular JS UNIT IV

table tr:nth-child(odd) {
background-color: #f2f2f2;
}
table tr:nth-child(even) {
background-color: #ffffff;
}
</style>
</head>
<body>
<h2>AngularJS Sample Application</h2>
<div ng-app = "mainApp" ng-controller = "studentController">
<table border = "0">
<tr>
<td>Enter first name:</td>
<td><input type = "text" ng-model = "student.firstName"></td>
</tr>
<tr>
<td>Enter last name: </td>
<td><input type = "text" ng-model = "student.lastName"></td>
</tr>
<tr>
<td>Name: </td>
<td>{{student.fullName()}}</td>
</tr>
<tr>
<td>Subject:</td>
<td>
<table>
<tr>
<th>Name</th>
<th>Marks</th>
</tr>
<tr ng-repeat = "subject in student.subjects">
<td>{{ subject.name }}</td>
Advanced Java Script-JQuery/AJAX/JSON/Angular JS UNIT IV

<td>{{ subject.marks }}</td>


</tr>
</table>

</td>
</tr>
</table>
</div>
</body>
</html>
mainApp.js
var mainApp = angular.module("mainApp", []);
studentController.js
mainApp.controller("studentController", function($scope) {
$scope.student = {
firstName: "Mahesh",
lastName: "Parashar",
fees:500,
subjects:[
{name:'Physics',marks:70},
{name:'Chemistry',marks:80},
{name:'Math',marks:65},
{name:'English',marks:75},
{name:'Hindi',marks:67}
],
fullName: function() {
var studentObject;
studentObject = $scope.student;
return studentObject.firstName + " " + studentObject.lastName;
}
};
});
Output
Open textAngularJS.htm in a web browser. See the result.
Advanced Java Script-JQuery/AJAX/JSON/Angular JS UNIT IV

7. Write about AngularJS controllers?


AngularJS controllers control the data of AngularJS applications. AngularJS
controllers are regular JavaScript Objects.
AngularJS Controllers
AngularJS applications are controlled by controllers. The ng-controller directive
defines the application controller. A controller is a JavaScript Object, created by a
standard JavaScript object constructor.
AngularJS Example
<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>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
});
</script>
Application explained:
1. The AngularJS application is defined by  ng-app="myApp". The application runs
inside the <div>.
2. The ng-controller="myCtrl" attribute is an AngularJS directive. It defines a
controller.
3. The myCtrl function is a JavaScript function.
4. AngularJS will invoke the controller with a $scope object.
5. In AngularJS, $scope is the application object (the owner of application variables
and functions).
6. The controller creates two properties (variables) in the scope
(firstName and lastName).
7. The ng-model directives bind the input fields to the controller properties
(firstName and lastName)
Advanced Java Script-JQuery/AJAX/JSON/Angular JS UNIT IV

Controller Methods
The example above demonstrated a controller object with two properties: lastName
and firstName. A controller can also have methods (variables as functions):
AngularJS Example
<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>
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>
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:
AngularJS Example
<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>
Advanced Java Script-JQuery/AJAX/JSON/Angular JS UNIT IV

8. Write about AngularJS scope?


The scope is the binding part between the HTML (view) and the JavaScript
(controller). The scope is an object with the available properties and methods. The
scope is available for both the view and the controller.
How to Use the Scope?
When you make a controller in AngularJS, you pass the $scope object as an
argument:
Example

Properties made in the controller, can be referred to in the view:

<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>

When adding properties to the $scope object in the controller, the view (HTML) gets
access to these properties.In the view, you do not use the prefix $scope, you just refer
to a propertyname, like {{carname}}.

Understanding the Scope

 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.


Advanced Java Script-JQuery/AJAX/JSON/Angular JS UNIT IV

The scope is a JavaScript object with properties and methods, which are available for
both the view and the controller.

Example

If you make changes in the view, the model and the controller will be updated:

<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>
Know Your Scope

It is important to know which scope you are dealing with, at any time.

In the two examples above there is only one scope, so knowing your scope is not an
issue, but for larger applications there can be sections in the HTML DOM which can
only access certain scopes.

Example

When dealing with the ng-repeat directive, each repetition has access to the current
repetition object:

<div ng-app="myApp" ng-controller="myCtrl">

<ul>
    <li ng-repeat="x in names">{{x}}</li>
</ul>

</div>
<script>
var app = angular.module('myApp', []);
Advanced Java Script-JQuery/AJAX/JSON/Angular JS UNIT IV

app.controller('myCtrl', function($scope) {
    $scope.names = ["Emil", "Tobias", "Linus"];
});

</script>

Each <li> element has access to the current repetition object, in this case a string,
which is referred to by using x.

Root Scope

All applications have a $rootScope which is the scope created on the HTML element
that contains the ng-app directive.

The rootScope is available in the entire application.

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.

Example

A variable named "color" exists in both the controller's scope and in the rootScope:

<body ng-app="myApp">

<p>The rootScope's favorite color:</p>

<h1>{{color}}</h1>

<div ng-controller="myCtrl">

<p>The scope of the controller's favorite color:</p>

<h1>{{color}}</h1>

</div>

<p>The rootScope's favorite color is still:</p>

<h1>{{color}}</h1>

<script>

var app = angular.module('myApp', []);

app.run(function($rootScope) {

$rootScope.color = 'blue';

});
Advanced Java Script-JQuery/AJAX/JSON/Angular JS UNIT IV

app.controller('myCtrl', function($scope) {

$scope.color = "red";

});

</script>

</body>
9. Explain AngularJS dependency? (injection AngularJS)?
Dependency Injection is a software design pattern in which components are given
their dependencies instead of hard coding them within the component. This relieves a
component from locating the dependency and makes dependencies configurable. This
helps in making components reusable, maintainable and testable.
AngularJS provides a supreme Dependency Injection mechanism. It provides
following core components which can be injected into each other as dependencies.
value
factory
service
provider
constant
value
value is simple javascript object and it is used to pass values to controller during
config phase.
//define a module
var mainApp = angular.module("mainApp", []);
//create a value object as "defaultInput" and pass it a data.
mainApp.value("defaultInput", 5);
...
//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);
}
});
factory
factory is a function which is used to return value. It creates value on demand
whenever a service or controller requires. It normally uses a factory function to
calculate and return the value.
//define a module
var mainApp = angular.module("mainApp", []);
Advanced Java Script-JQuery/AJAX/JSON/Angular JS UNIT IV

//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;
});

//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);
}
});
...
service
service is a singleton javascript object containing a set of functions to perform certain
tasks. Services are defined using service() functions and then injected into 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);
}
});
//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);
}
});
provider
provider is used by AngularJS internally to create services, factory etc. during config
phase(phase during which AngularJS bootstraps itself). Below mention script can be
used to create MathService that we've created earlier. Provider is a special factory
method with a method get() which is used to return the value/service/factory.
Advanced Java Script-JQuery/AJAX/JSON/Angular JS UNIT IV

//define a module
var mainApp = angular.module("mainApp", []);
...
//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;
};
});
});
constant
constants are used to pass values at config phase considering the fact that value can
not be used to be passed during config phase.
mainApp.constant("configParam", "constant value");
10. Write about AngularJS data bindings?

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.

AngularJS follows Two-Way data binding model.

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.
Advanced Java Script-JQuery/AJAX/JSON/Angular JS UNIT IV

Two-Way Data Binding

Data-binding in Angular apps is the automatic synchronization of data between the


model and view components.

Data binding lets you treat the model as the single-source-of-truth in your application.
The view is a projection of the model at all times. If the model is changed, the view
reflects the change and vice versa.

<!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="firstName='Ajeet'">


Advanced Java Script-JQuery/AJAX/JSON/Angular JS UNIT IV

<p>Input something in the input box:</p>

<p>Name: <input type="text" ng-model="firstName"></p>

<p>You wrote: {{ firstName }}</p>

</div>

</body>

</html>

In the above example, the {{ firstName }} expression is an AngularJS data binding


expression. Data binding in AngularJS binds AngularJS expressions with AngularJS
data.

{{ firstName }} is bound with ng-model="firstName".

Let's take another example where two text fields are bound together with two ng-
model directives:

<!DOCTYPE html>

<html>

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></
script>

<body>

<div data-ng-app="" data-ng-init="quantity=1;price=20">

<h2>Cost Calculator</h2>

Quantity: <input type="number" ng-model="quantity">

Price: <input type="number" ng-model="price">

<p><b>Total in rupees:</b> {{quantity * price}}</p>

</div>

</body>

</html>

11. Explain AngularJS $watch function?


Advanced Java Script-JQuery/AJAX/JSON/Angular JS UNIT IV

The AngularJS $scope functions $watch(), $digest() and $apply() are some of the


central functions in AngularJS. Understanding $watch(), $digest() and $apply() is
essential in order to understand AngularJS.
When you create a data binding from somewhere in your view to a variable on
the $scope object, AngularJS creates a "watch" internally. A watch means that
AngularJS watches changes in the variable on the $scope object. The framework is
"watching" the variable. Watches are created using the$scope.$watch() function 
$watch()
The $scope.watch() function creates a watch of some variable. When you register a
watch you pass two functions as parameters to the $watch() function:
 A value function
 A listener function
Here is an example:

$scope.$watch(function() {},

function() {}

);
The first function is the value function and the second function is the listener function.
The value function should return the value which is being watched. AngularJS can
then check the value returned against the value the watch function returned the last
time. That way AngularJS can determine if the value has changed. Here is an
example:
$scope.$watch(function(scope) { return scope.data.myVar },
function() {}
);
This example value function returns the $scope variable scope.data.myVar. If the
value of this variable changes, a different value will be returned, and AngularJS will
call the listener function.
Notice how the value function takes the scope as parameter (without the $ in
the name). Via this parameter the value function can access the $scope and its
variables. The value function can also watch global variables instead if you need that,
but most often you will watch a $scope variable.
Advanced Java Script-JQuery/AJAX/JSON/Angular JS UNIT IV

The listener function should do whatever it needs to do if the value has


changed. Perhaps you need to change the content of another variable, or set the
content of an HTML element or something. Here is an example:
$scope.$watch(function(scope) { return scope.data.myVar },
function(newValue, oldValue) {
document.getElementById("").innerHTML =
"" + newValue + "";
}
);
This example sets the inner HTML of an HTML element to the new value of the
variable, embedded in theb element which makes the value bold. Of course you could
have done this using the code {{ data.myVar }, but this is just an example of what
you can do inside the listener function.
12. Write filters in AngularJS?
Filters are used to change modify the data and can be clubbed in
expression or directives using pipe character. Following is the list of
commonly used filters.

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.

Uppercase filter
Add uppercase filter to an expression using pipe character. Here we've added
uppercase filter to print student name in all capital letters.

Enter first name:<input type = "text" ng-model = "student.firstName">

Enter last name: <input type = "text" ng-model = "student.lastName">


Name in Upper Case: {{student.fullName() | uppercase}}

Lowercase filter
Advanced Java Script-JQuery/AJAX/JSON/Angular JS UNIT IV

Add lowercase filter to an expression using pipe character. Here we've added
lowercase filter to print student name in all lowercase letters.

Currency filter

Enter first name:<input type = "text" ng-model = "student.firstName">

Enter last name: <input type = "text" ng-model = "student.lastName">


Name in Lower Case: {{student.fullName() | lowercase}}
Add currency filter to an expression returning number using pipe character. Here
we've added currency filter to print fees using currency format.

Enter fees: <input type = "text" ng-model = "student.fees">


fees: {{student.fees | currency}}

Filter filter
To display only required subjects, we've used subjectName as filter.

Enter subject: <input type = "text" ng-model = "subjectName">

Subject:

<ul>

<li ng-repeat = "subject in student.subjects | filter: subjectName">

{{ subject.name + ', marks:' + subject.marks }}

</li>
</ul>

Orderby filter
To order subjects by marks, we've used orderBy marks.

Subject:

<ul>

<li ng-repeat = "subject in student.subjects | orderBy:'marks'">

{{ subject.name + ', marks:' + subject.marks }}

</li>
Advanced Java Script-JQuery/AJAX/JSON/Angular JS UNIT IV

</ul>

Example

Following example will showcase all the above mentioned filters.

testAngularJS.htm

<html>

<head>

<title>Angular JS Filters</title>

<script src =
"https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>

</head>

<body>

<h2>AngularJS Sample Application</h2>

<div ng-app = "mainApp" ng-controller = "studentController">

<table border = "0">

<tr>

<td>Enter first name:</td>

<td><input type = "text" ng-model = "student.firstName"></td>

</tr>

<tr>

<td>Enter last name: </td>

<td><input type = "text" ng-model = "student.lastName"></td>

</tr>

<tr>
Advanced Java Script-JQuery/AJAX/JSON/Angular JS UNIT IV

<td>Enter fees: </td>

<td><input type = "text" ng-model = "student.fees"></td>

</tr>

<tr>

<td>Enter subject: </td>

<td><input type = "text" ng-model = "subjectName"></td>

</tr>

</table>

<br/>

<table border = "0">

<tr>

<td>Name in Upper Case: </td><td>{{student.fullName() |


uppercase}}</td>

</tr>

<tr>

<td>Name in Lower Case: </td><td>{{student.fullName() |


lowercase}}</td>

</tr>

<tr>

<td>fees: </td><td>{{student.fees | currency}}

</td>

</tr>

<tr>

<td>Subject:</td>
Advanced Java Script-JQuery/AJAX/JSON/Angular JS UNIT IV

<td>

<ul>

<li ng-repeat = "subject in student.subjects | filter: subjectName |


orderBy:'marks'">

{{ subject.name + ', marks:' + subject.marks }}

</li>

</ul>

</td>

</tr>

</table>

</div>

<script>

var mainApp = angular.module("mainApp", []);

mainApp.controller('studentController', function($scope) {

$scope.student = {

firstName: "Mahesh",

lastName: "Parashar",

fees:500,

subjects:[

{name:'Physics',marks:70},

{name:'Chemistry',marks:80},

{name:'Math',marks:65}

],
Advanced Java Script-JQuery/AJAX/JSON/Angular JS UNIT IV

fullName: function() {

var studentObject;

studentObject = $scope.student;

return studentObject.firstName + " " + studentObject.lastName;

};

});

</script>

</body>
</html>

Output
Open textAngularJS.htm in a web browser. See the result
13. Write about AngularJS events?
AngularJS enriches form filling and validation. We can use ng-click to handle
AngularJS click on button and use $dirty and $invalid flags to do the validations in
seemless way. Use novalidate with a form declaration to disable any browser specific
validation. Forms controls makes heavy use of Angular events. Let's have a quick
look on events first.

Events
AngularJS provides multiple events which can be associated with the HTML
controls. For example ng-click is normally associated with button. Following are
supported events in Angular JS.

 ng-click

 ng-dbl-click
 ng-mousedown
 ng-mouseup
 ng-mouseenter
 ng-mouseleave
Advanced Java Script-JQuery/AJAX/JSON/Angular JS UNIT IV

 ng-mousemove
 ng-mouseover
 ng-keydown
 ng-keyup
 ng-keypress
 ng-change

ng-click
Reset data of a form using on-click directive of a button.

<input name = "firstname" type = "text" ng-model = "firstName" required>

<input name = "lastname" type = "text" ng-model = "lastName" required>

<input name = "email" type = "email" ng-model = "email" required>

<button ng-click = "reset()">Reset</button>

<script>

function studentController($scope) {

$scope.reset = function(){

$scope.firstName = "Mahesh";

$scope.lastName = "Parashar";

$scope.email = "[email protected]";

$scope.reset();

</script>

Validate data
Advanced Java Script-JQuery/AJAX/JSON/Angular JS UNIT IV

Following can be used to track error.

 $dirty − states that value has been changed.

 $invalid − states that value entered is invalid.

 $error − states the exact error.

Example
Following example will showcase all the above mentioned directives.

testAngularJS.htm

<html>
<head>
<title>Angular JS Forms</title>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<style>
table, th , td {
border: 1px solid grey;
border-collapse: collapse;
padding: 5px;
}
table tr:nth-child(odd) {
background-color: #f2f2f2;
}
table tr:nth-child(even) {
background-color: #ffffff;
}
</style>
</head>
<body>
<h2>AngularJS Sample Application</h2>
<div ng-app = "mainApp" ng-controller = "studentController">
<form name = "studentForm" novalidate>
Advanced Java Script-JQuery/AJAX/JSON/Angular JS UNIT IV

<table border = "0">


<tr>
<td>Enter first name:</td>
<td><input name = "firstname" type = "text" ng-model = "firstName" required>
<span style = "color:red" ng-show = "studentForm.firstname.$dirty &&
studentForm.firstname.$invalid">
<span ng-show = "studentForm.firstname.$error.required">First Name is
required.</span>
</span>
</td>
</tr>
<tr>
<td>Enter last name: </td>
<td><input name = "lastname" type = "text" ng-model = "lastName" required>
<span style = "color:red" ng-show = "studentForm.lastname.$dirty &&
studentForm.lastname.$invalid">
<span ng-show = "studentForm.lastname.$error.required">Last Name is
required.</span>
</span>
</td>
</tr>
<tr>
<td>Email: </td><td><input name = "email" type = "email" ng-model = "email" length
= "100" required>
<span style = "color:red" ng-show = "studentForm.email.$dirty &&
studentForm.email.$invalid">
<span ng-show = "studentForm.email.$error.required">Email is required.</span>
<span ng-show = "studentForm.email.$error.email">Invalid email address.</span>
</span>
</td>
</tr>
Advanced Java Script-JQuery/AJAX/JSON/Angular JS UNIT IV

<tr>
<td>
<button ng-click = "reset()">Reset</button>
</td>
<td>
<button ng-disabled = "studentForm.firstname.$dirty &&
studentForm.firstname.$invalid || studentForm.lastname.$dirty &&
studentForm.lastname.$invalid || studentForm.email.$dirty &&
studentForm.email.$invalid" ng-click="submit()">Submit</button>
</td>
</tr>
</table>
</form>
</div>
<script>
var mainApp = angular.module("mainApp", []);
mainApp.controller('studentController', function($scope) {
$scope.reset = function(){
$scope.firstName = "Mahesh";
$scope.lastName = "Parashar";
$scope.email = "[email protected]";
}
$scope.reset();
});
</script>
</body>
</html>
Output
Open textAngularJS.htm in a web browser. See the result.

14. Write about AngularJS AJAX functions?


Advanced Java Script-JQuery/AJAX/JSON/Angular JS UNIT IV

AngularJS provides $https: control which works as a service to read data from the
server. The server makes a database call to get the desired records. AngularJS needs
data in JSON format. Once the data is ready, $https: can be used to get the data from
server
$http is an AngularJS service for reading data from remote servers.
AngularJS $http
The AngularJS $http service makes a request to the server, and returns a response.
Example
Make a simple request to the server, and display the result in a header:

<div ng-app="myApp" ng-controller="myCtrl">

<p>Today's welcome message is:</p>

<h1>{{myWelcome}}</h1>

</div>

<script>

var app = angular.module('myApp', []);

app.controller('myCtrl', function($scope, $http) {

$http.get("welcome.htm")

.then(function(response) {

$scope.myWelcome = response.data;

});

});

</script>

Methods

The example above uses the .get method of the $http service.

The .get method is a shortcut method of the $http service. There are several shortcut
methods:

.delete()
Advanced Java Script-JQuery/AJAX/JSON/Angular JS UNIT IV

.get()

.head()

.jsonp()

.patch()

.post()

.put()

The methods above are all shortcuts of calling the $http service:

Example

var app = angular.module('myApp', []);

app.controller('myCtrl', function($scope, $http) {

$http({

method : "GET",

url : "welcome.htm"

}).then(function mySuccess(response) {

$scope.myWelcome = response.data;

}, function myError(response) {

$scope.myWelcome = response.statusText;

});

});

The example above executes the $http service with an object as an argument. The
object is specifying the HTTP method, the url, what to do on success, and what to do
on failure.

Properties

The response from the server is an object with these properties:

.config the object used to generate the request.

.data a string, or an object, carrying the response from the server.


Advanced Java Script-JQuery/AJAX/JSON/Angular JS UNIT IV

.headers a function to use to get header information.

.status a number defining the HTTP status.

.statusText a string defining the HTTP status.

Example

var app = angular.module('myApp', []);

app.controller('myCtrl', function($scope, $http) {

$http.get("welcome.htm")

.then(function(response) {

$scope.content = response.data;

$scope.statuscode = response.status;

$scope.statustext = response.statusText;

});

});

To handle errors, add one more functions to the .then method:

Example

var app = angular.module('myApp', []);

app.controller('myCtrl', function($scope, $http) {

$http.get("wrongfilename.htm")

.then(function(response) {

//First function handles success

$scope.content = response.data;

}, function(response) {

//Second function handles error

$scope.content = "Something went wrong";

});
Advanced Java Script-JQuery/AJAX/JSON/Angular JS UNIT IV

});

JSON

The data you get from the response is expected to be in JSON format.JSON is a great
way of transporting data, and it is easy to use within AngularJS, or any other
JavaScript.

Example: On the server we have a file that returns a JSON object containing 15
customers, all wrapped in array called records.

Example

The ng-repeat directive is perfect for looping through an array:

<div ng-app="myApp" ng-controller="customersCtrl">

<ul>

<li ng-repeat="x in myData">

{{ x.Name + ', ' + x.Country }}

</li>

</ul>

</div>

<script>

var app = angular.module('myApp', []);

app.controller('customersCtrl', function($scope, $http) {

$http.get("customers.php").then(function(response) {

$scope.myData = response.data.records;

});

});

</script>

Application explained:
The application defines the customersCtrl controller, with a $scope and $http object.
Advanced Java Script-JQuery/AJAX/JSON/Angular JS UNIT IV

$http is an XMLHttpRequest object for requesting external data.$http.get() reads


JSON data from https://www.w3schools.com/angular/customers.php.On success, the
controller creates a property, myData, in the scope, with JSON data from the server.
15. Explain the process of creating AngularJS with json arrays?

AngularJS Arrays

Expressions can be used to work with arrays as well. Let's look at an example of
Angular JS expressions with arrays. In this example, we are going to define an array
which is going to hold the marks of a student in 3 subjects. In the view, we will
display the value of these marks accordingly.

Code Explanation:
1. The ng-init directive is used define the array with the name "marks" with 3
values of 1, 15 and 19.
2. We are then using expressions of marks [index] to access each element of the
array.
If the code is executed successfully, the following Output will be shown when you
run your code in the browser.
Output:
Advanced Java Script-JQuery/AJAX/JSON/Angular JS UNIT IV

From the output, it can be clearly seen that the marks being displayed, that are defined
in the array.

16. Write an example program to to design and execute AngularJS registration


form and login form?

Html form:

<body ng-controller="RegisterCtrl" ng-app="myApp">

<div class="container">

<div id="signup">

<div class="signup-screen">

<div class="space-bot text-center">

<h1>Sign up</h1>

<div class="divider"></div>

</div>

<form class="form-register" method="post" name="register" novalidate>

<div class="input-field col s6">

<input id="first-name" type="text" class="validate" required>

<label for="first-name">First Name</label>

</div>

<div class="input-field col s6">


Advanced Java Script-JQuery/AJAX/JSON/Angular JS UNIT IV

<input id="last-name" type="text" class="validate" required>

<label for="last-name">Last Name</label>

</div>

<div class="input-field col s6">

<input id="email" type="email" name="email" ng-model="email" class="validate"


required>

<label for="email">Email</label>

</div>

<p class="alert alert-danger" ng-show="form-register.email.$error.email">Your


email is invalid.</p>

<div class="input-field col s6">

<input id="password" type="password" name="password" ng-model="password"


ng-minlength='6' class="validate" required>

<label for="password">Password</label>

</div>

<p class="alert alert-danger" ng-show="form-register.password.$error.minlength ||


form.password.$invalid">Your password must be at least 6 characters.</p>

<div class="space-top text-center">

<button ng-disabled="form-register.$invalid" class="waves-effect waves-light btn


done">

<i class="material-icons left">done</i> Done

</button>

<button type="button" class="waves-effect waves-light btn cancel">

<i class="material-icons left">clear</i>Cancel

</button>

</div>

</form>

</div>
Advanced Java Script-JQuery/AJAX/JSON/Angular JS UNIT IV

</div>

</div>

</body>

Css file:

body {

min-height:100%;

background-color: #263238;

.text-center{

text-align: center;

.space-bot{

margin-bottom: 35px;

.space-top{

margin-top: 35px;

/* Title */

h1 {

color: white;

font-family: 'Roboto';

text-transform: uppercase;

font-weight: 900;

font-size: 25px;
Advanced Java Script-JQuery/AJAX/JSON/Angular JS UNIT IV

text-align: center;

/* Sign Up */

.container {

max-width: 400px;

max-height: 100px;

margin-top: 10px;

.alert-danger{

text-align: center;

.signup-screen {

padding: 20px;

padding-bottom: 40px;

border-radius: 5px;

background-color: #2c3940;

box-shadow: 0 1px 6px rgba(0,0,0,.3);

color: white;

.btn{

border-radius: 2px;

.cancel{

background-color: #df405a;
Advanced Java Script-JQuery/AJAX/JSON/Angular JS UNIT IV

.done{

background-color: #5CAB7D;

.done:hover{

background-color: #6dc793;

.done:focus{

background-color: #6dc793;

.cancel:hover{

background-color: #f0435f;

.cancel:focus{

background-color: #f0435f;

.input-group {

width:100%;

.input-group .ng-invalid {

border: 2px solid #e74c3c;

border-radius: 3px;

/* Error Box */

.alert{
Advanced Java Script-JQuery/AJAX/JSON/Angular JS UNIT IV

padding: 15px;

margin-bottom: 20px;

border: 1px solid transparent;

border-radius: 2px;

border-color: #e85a71;

background-color: #e85a71;

color: white;

.help-block {

font-size: 12px;

color: white

Js file:

var myApp = angular.module("myApp", []);

myApp.controller("RegisterCtrl", function ($scope) {

});

17. Explain AngularJS CRUD operations with example?

Step 1: Firstly setup the project for performing crud operation

Step 2: in this we use angularjs library for use angularjs functionality and bootstrap
css for good looking.

<link href="~/Content/bootstrap.min.css" rel="stylesheet" />

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></
script>

Step 3: in this step we design html page

Crud.cshtml:
Advanced Java Script-JQuery/AJAX/JSON/Angular JS UNIT IV

<div ng-app="MyApp" class="container" ng-controller="Book">

<table class="table table-striped table-bordered">

<tr>

<td>ID</td>

<td>

<input type="text" class="form-control" ng-model="item.id" /></td>

</tr>

<tr>

<td>Name</td>

<td>

<input type="text" class="form-control" ng-model="item.name" /></td>

</tr>

<tr>

<td>EmailID</td>

<td>

<input type="text" class="form-control" ng-model="item.email" /></td>

</tr>

<tr>

<td>Password</td>

<td>

<input type="password" class="form-control" ng-model="item.password" /></td>

</tr>

<tr>

<td>Phone</td>

<td>
Advanced Java Script-JQuery/AJAX/JSON/Angular JS UNIT IV

<input type="text" class="form-control" ng-model="item.phone" /></td>

</tr>

<tr>

<td class="text-right" colspan="2">

<button ng-click="addItem(item)" class="btn btn-primary">

Add

</button>

</td>

</tr>

</table>

<table class="table table-striped table-bordered">

<thead>

<tr>

<th>ID</th>

<th>Name</th>

<th>EmailID</th>

<th>Phone</th>

<th>Edit</th>

<th>Remove</th>

</tr>

</thead>

<tbody>

<tr ng-repeat="item in items">

<td><span ng-hide="editMode">{{item.id}}</span>

<input type="text" ng-show="editMode" ng-model="item.id" />


Advanced Java Script-JQuery/AJAX/JSON/Angular JS UNIT IV

</td>

<td>

<span ng-hide="editMode">{{item.name}}</span>

<input type="text" ng-show="editMode" ng-model="item.name" />

</td>

<td>

<span ng-hide="editMode">{{item.email}}</span>

<input type="text" ng-show="editMode" ng-model="item.email" />

</td>

<td>

<span ng-hide="editMode">{{item.phone}}</span>

<input type="text" ng-show="editMode" ng-model="item.phone" />

</td>

<td>

<i ng-hide="editMode" ng-click="editMode = true; editItem(item)" class="glyphicon


glyphicon-edit"></i>

<i class="glyphicon glyphicon-saved" ng-show="editMode" ng-click="editMode =


false"></i>

</td>

<td>

<i ng-click="removeItem($index)" class="glyphicon glyphicon-trash"></i>

</td>

</tr>

</tbody>

</table>

</div>
Advanced Java Script-JQuery/AJAX/JSON/Angular JS UNIT IV

Step 4: Now write angular js code.

<script>

var app = angular.module('MyApp', []);

app.controller("Book", function ($scope) {

$scope.items = [];

$scope.addItem = function (item) {

$scope.items.push(item);

$scope.item = {};

},

$scope.removeItem = function (index) {

console.log(index);

$scope.items.splice(index, 1)

},

$scope.editItem = function (index) {

$scope.editing = $scope.items.indexOf(index);

});

</script>

18. Explain angularjs animations?

AngularJS provides animated transitions, with help from CSS.

What is an Animation?

An animation is when the transformation of an HTML element gives you an illusion


of motion.

Example:

Check the checkbox to hide the DIV:

<body ng-app="ngAnimate">
Advanced Java Script-JQuery/AJAX/JSON/Angular JS UNIT IV

Hide the DIV: <input type="checkbox" ng-model="myCheck">

<div ng-hide="myCheck"></div>

</body>

Applications should not be filled with animations, but some animations can make the
application easier to understand.
What do I Need Animations?
To make your applications ready for animations, you must include the AngularJS
Animate library:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-
animate.js"></script>
Then you must refer to the ngAnimate module in your application:

<body ng-app="ngAnimate">

Or if your application has a name, add ngAnimate as a dependency in your


application module:

Example

<body ng-app="myApp">

<h1>Hide the DIV: <input type="checkbox" ng-model="myCheck"></h1>

<div ng-hide="myCheck"></div>

<script>

var app = angular.module('myApp', ['ngAnimate']);

</script>

What Does ngAnimate Do?


The ngAnimate module adds and removes classes.The ngAnimate module does not
animate your HTML elements, but when ngAnimate notice certain events, like hide or
show of an HTML element, the element gets some pre-defined classes which can be
used to make animations.

The directives in AngularJS who add/remove classes are:

ng-show
Advanced Java Script-JQuery/AJAX/JSON/Angular JS UNIT IV

ng-hide

ng-class

ng-view

ng-include

ng-repeat

ng-if

ng-switch

The ng-show and ng-hide directives adds or removes a ng-hide class value.

The other directives adds a ng-enter class value when they enter the DOM, and a ng-
leave attribute when they are removed from the DOM. The ng-repeat directive also
adds a ng-move class value when the HTML element changes position. In addition,
during the animation, the HTML element will have a set of class values, which will be
removed when the animation has finished. Example: the ng-hide directive will add
these class values:
ng-animate
ng-hide-animate
ng-hide-add (if the element will be hidden)
ng-hide-remove (if the element will be showed)
ng-hide-add-active (if the element will be hidden)
ng-hide-remove-active (if the element will be showed)
Animations Using CSS
We can use CSS transitions or CSS animations to animate HTML elements.
CSS Transitions
CSS transitions allows you to change CSS property values smoothly, from one value
to another, over a given duration:
Example:
When the DIV element gets the .ng-hide class, the transition will take 0.5 seconds,
and the height will smoothly change from 100px to 0:
<style>
Advanced Java Script-JQuery/AJAX/JSON/Angular JS UNIT IV

div {

transition: all linear 0.5s;

background-color: lightblue;

height: 100px;

.ng-hide {

height: 0;

</style>

CSS Animations

CSS Animations allows you to change CSS property values smoothly, from one value
to another, over a given duration:

Example:

When the DIV element gets the .ng-hide class, the myChange animation will run,
which will smoothly change the height from 100px to 0:

<style>

@keyframes myChange {

from {

height: 100px;

} to {

height: 0;

div {

height: 100px;
Advanced Java Script-JQuery/AJAX/JSON/Angular JS UNIT IV

background-color: lightblue;

div.ng-hide {

animation: 0.5s myChange;

</style>

19. Explain angularjs validations?


AngularJS offers client-side form validation. AngularJS monitors the state of the form
and input fields (input, textarea, select), and lets you notify the user about the current
state. AngularJS also holds information about whether they have been touched, or
modified, or not. You can use standard HTML5 attributes to validate input, or you can
make your own validation functions. Client-side validation cannot alone secure user
input. Server side validation is also necessary.
Angular built-in validation directives
The validations of each field can be declared directly in HTML. For example, the
password field has the following validations:
 field is mandatory
 minimum length of 6 characters
 maximum length of 10 characters
These validations are declared using the required, ng-minlength and
ng-maxlength directives:
<input name="password" ng-model="user.password" type="password"
placeholder="Password"
required ng-minlength="6" ng-maxlength="10">
here the full list of built-in directives that can be applied to a form input. It's also
possible to create our own validation directives.
Enhanced form validation with ng-messages
While the user is entering data, it's helpful to show a message informing him of the
next step in the validation process, for example:
 first show that a field is required
 when the user starts typing, show a message indicating the minimum length
Advanced Java Script-JQuery/AJAX/JSON/Angular JS UNIT IV

This is how the form should look with several of it's components dirty and invalid:
This functionality can be implemented using the ng-messages directive:
<div class="pure-control-group">
<label>Password</label>
<input name="password" ng-model="user.password"
type="password" placeholder="Password"
required ng-minlength="6" ng-maxlength="10">
<div class="field-message"
ng-messages="frm.password.$error"
ng-if='frm.password.$dirty' ng-cloak>
<div ng-message="required">Password is required</div>
<div ng-message="minlength">
Password must have minimum 6 characters
</div>
<div ng-message="maxlength">
Password must have maximum 10 characters
</div>
</div>
</div>
Controlling the state of the submit button
The submit button can be made enabled/disabled according to the form validity and
the condition checkbox using the ng-disabled directive:
<button type="submit" class="pure-button pure-button-primary"
ng-disabled="frm.$invalid || !conditions">Submit</button>
20. Explain AngularJS $q?
$q is an angular define a service. It’s same as new Promise(). But $q takes things to
the next level by enhancing additional feature that developers can use to perform
complex tasks more simply.
This is a sample for creating promise using $q
angular.module("app",[])
.controller("ctrl",function($scope,$q){
var work = "resolve";
var promise = $q(function(resolve, reject) {
if (work === "resolve") {
Advanced Java Script-JQuery/AJAX/JSON/Angular JS UNIT IV

resolve('response 1!');
} else {
reject('Oops... something went wrong');
}
});
promise.then(function(data) {
alert(data)
})
})

$q.defer()
$q.defer() return the instance of the promise constructor. Once you create a defer
object there are following methods and properties that you can access from that object
resolve(value) – resolves the derived promise with the value. If the value is a
rejection constructed via $q.reject, the promise will be rejected instead.
reject(reason) – rejects the derived promise with the reason. This is equivalent to
resolving it with a rejection constructed via $q.reject.
notify(value) - provides updates on the status of the promise's execution. This may be
called multiple times before the promise is either resolved or rejected.
promise – {Promise} – promise object associated with this deferred
example
angular.module("app",[])
.controller("ctrl",function($scope,$q){
var work = "resolve";
function getData(){
var obj = $q.defer();
if (work === "resolve") {
obj.resolve('response 1!');
} else {
obj.reject('Oops... something went wrong');
}
return obj.promise;
}
Advanced Java Script-JQuery/AJAX/JSON/Angular JS UNIT IV

getData().then(function(data) {
alert(data)
})
})
$q.all()
If a user need to send multiple request one shot,then the user can use $q.all() service.

$q.all([$http.get('data1.json'),$http.get('data2.json')])
.then(function(response){
console.log(response[0].data) // data1.json response
console.log(response[1].data) // data1.json response
})
In here, there are two http request sent simultaneously to two separate json files to get
data. The response comes as an array and response order is same as the http request
order.
$q.race()
$q.race() is very similar to $q.all(). But instead of sending response of each request, it
will only return the one request response. Specifically, only return the response of
first request that been executed. That does not mean it’s not going to send other
requests. All the requests are sending but it's only return the response of the first
request that executed.
$q.race([$http.get('data1.json'),$http.get('data2.json')])
.then(function(response){
console.log(response[0].data) // return one response
})
In here response can be either data1.Json or data2.json. That's the downfall of using
this method. Since its return the response of the first executed request, can’t be sure
which request response will resolved by the promise. This method useful for bulk
requests which you don’t want to see the response of all the requests
Conclusion
Use $q for constructing promises from non-promise Objects/callbacks, and utilize
$q.all() and $q.race() to work with existing promises.
Advanced Java Script-JQuery/AJAX/JSON/Angular JS UNIT IV

21. Explain AngularJS custom services, values, factories, services, directives and
providers?
Custom values: A value is nothing more than a simple injectable value. The value
can be a string, number but also a function. Value differs from constant in that value
can not be injected into configurations, but it can be intercepted by decorators.
angular.module('app', []);
.value('movieTitle', 'The Matrix');
.controller('MyController', function (movieTitle) {
expect(movieTitle).toEqual('The Matrix');
})
Custom Services: A service is a constructor function which creates the object using
new keyword. You can add properties and functions to a service object by using this
keyword. Unlike factory, it doesn’t return anything.
Syntax
app.service('serviceName',function(){})
Creating service using service method
<script>
//creating module
var app = angular.module('app', []); 
//define a service using service() function
app.service('MyService', function () {
this.function1 = function () {
//TO DO:
};
  this.function2 = function () {
//TO DO:
};
});
</script>
When to use: It is a singleton object. Use it when you need to share a single object
across the application. For example, authenticated user details.
Custom Factory: A factory is a simple function which allows you to add some logic
before creating the object. It returns the created object.
Advanced Java Script-JQuery/AJAX/JSON/Angular JS UNIT IV

Syntax
app.factory('serviceName',function(){ return serviceObj;})
Creating service using factory method
<script>
//creating module
var app = angular.module('app', []); 
//define a factory using factory() function
app.factory('MyFactory', function () { 
var serviceObj = {};
serviceObj.function1 = function () {
//TO DO:
}; 
serviceObj.function2 = function () {
//TO DO:
}; 
return serviceObj;
});
</script>
When to use: It is just a collection of functions like a class. Hence, it can be
instantiated in different controllers when you are using it with constructor function.
Custom Providers: A provider is used to create a configurable service object. It
returns value by using $get() function.
Syntax
//creating a service
app.provider('serviceName',function(){}); 
//configuring the service
app.config(function(serviceNameProvider){});
Creating service using provider method
<script>
//define a provider using provider() function
app.provider('configurableService', function () {
var name = '';
this.setName = function (newName) {
name = newName;
Advanced Java Script-JQuery/AJAX/JSON/Angular JS UNIT IV

};
this.$get = function () {
return name;
};
}); 
//configuring provider using config() function
app.config(function (configurableService) {
configurableService.setName('www.dotnet-tricks.com');
});
</script>
When to use: When you need to provide module-wise configuration for your service
object before making it available.
Custom directives: Examples of directives are the interpolation directive ( {{ }} ),
the ng-repeat directive and ng-if directive. It is possible to implement your own
directives too. This is what AngularJS refers to as "teaching HTML new tricks". This
text will show you how to do that.

Directive Types

You can implement the following types of directives:


 Element directives
 Attribute directives
 CSS class directives
 Comment directives
Of these, AngularJS recommends that you try to use element and attribute directives,
and leave the CSS class and comment directives (unless absolutely necessary). The
type of a directive determines how the directive is activated. An element directive is
activated when AngularJS finds a matching HTML element in the HTML template.
An attribute directive is activated when AngularJS finds a matching HTML element
attribute. A CSS class directive is activated when AngularJS finds a matching CSS
Class. And, a comment directive is activated when AngularJS finds a matching
HTML comment.
A Basic Directive
You register a directive with a module. Here is an example of how that looks:
myapp = angular.module("myapp", []);
Advanced Java Script-JQuery/AJAX/JSON/Angular JS UNIT IV

myapp.directive('div', function() {
var directive = {};
directive.restrict = 'E'; /* restrict this directive to elements */
directive.template = "My first directive: {{textToInsert}}";
return directive;
});
22. Explain AngularJS Routing, AngularUI Routing?
The ngRoute module helps your application to become a Single Page Application.
What is 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.
Example:
Navigate to "red.htm", "green.htm", and "blue.htm":
<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>
<div ng-view></div>
<script>
var app = angular.module("myApp", ["ngRoute"]);
app.config(function($routeProvider) {
    $routeProvider
    .when("/", {
        templateUrl : "main.htm"
    })
    .when("/red", {
        templateUrl : "red.htm"
    })
    .when("/green", {
        templateUrl : "green.htm"
Advanced Java Script-JQuery/AJAX/JSON/Angular JS UNIT IV

    })
    .when("/blue", {
        templateUrl : "blue.htm"
    });
});
</script>
</body>
The ngRoute module helps your application to become a Single Page Application.
What is 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.
Example:
Navigate to "red.htm", "green.htm", and "blue.htm":
<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>
<div ng-view></div>
<script>
var app = angular.module("myApp", ["ngRoute"]);
app.config(function($routeProvider) {
$routeProvider
.when("/", {
templateUrl : "main.htm"
})
.when("/red", {
templateUrl : "red.htm"
})
.when("/green", {
templateUrl : "green.htm"
})
Advanced Java Script-JQuery/AJAX/JSON/Angular JS UNIT IV

.when("/blue", {
templateUrl : "blue.htm"
});
});
</script>
</body>
Where Does it Go?
Your application needs a container to put the content provided by the routing.

This container is the ng-view directive.


There are three different ways to include the ng-view directive in your application:
Example:
<div ng-view></div>
<ng-view></ng-view>
<div class="ng-view"></div>
Applications can only have one ng-view directive, and this will be the placeholder for
all views provided by the route.
$routeProvider
With the $routeProvider you can define what page to display when a user clicks a
link.
Example:
Define a $routeProvider:
var app = angular.module("myApp", ["ngRoute"]);
app.config(function($routeProvider) {
    $routeProvider
    .when("/", {
        templateUrl : "main.htm"
    })
    .when("/london", {
        templateUrl : "london.htm"
    })
    .when("/paris", {
        templateUrl : "paris.htm"
Advanced Java Script-JQuery/AJAX/JSON/Angular JS UNIT IV

    });
});
Define the $routeProvider using the config method of your application. Work
registered in the config method will be performed when the application is loading.
23.

You might also like