0% found this document useful (0 votes)
39 views18 pages

Unit 4

Uploaded by

Suchi Patel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views18 pages

Unit 4

Uploaded by

Suchi Patel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

Unit-4: Angular JS

4.1 Concepts and characteristics of Angular JS


• Angular JS is an open-source JavaScript framework that is used to build
web applications. It can be freely used, changed and shared by anyone.
• AngularJS is a JavaScript framework for building MVC-based web
applications. It allows you to split the business logic layer, data layer, and
presentation layer.
• Angular JS is developed by Google.
• It is an excellent framework for building single phase applications and line
of business applications.
• 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.

Features

• MVC – The framework is built on the famous concept of MVC (Model-


View-Controller). This is a design pattern used in all modern-day web
applications. This pattern is based on splitting the business logic layer, the
data layer, and presentation layer into separate sections. The division into
different sections is done so that each one could be managed more easily.

• Data Model Binding – You don’t need to write special code to bind data
to the HTML controls. This can be done by Angular by just adding a few
snippets of code.

• Writing less code – When carrying out DOM manipulation a lot of


JavaScript was required to be written to design any application. But with
Angular, you will be amazed with the lesser amount of code you need to
write for DOM manipulation.
• Unit Testing ready – The designers at Google not only developed Angular
but also developed a testing framework called “Karma” which helps in
designing unit tests for AngularJS applications.

4.1.1 Expressions in Angular JS (Numbers, Strings, Objects,


Arrays)
Unit-4: Angular JS

• In AngularJS, expressions are used to bind application data to HTML.


AngularJS resolves the expression, and return the result exactly where the
expression is written.
• Expressions are written inside double braces {{expression}}.They can also
be written inside a directive: ng-bind="expression".
• Example: {{ 5 + 5 }} or {{ firstName + " " + lastName }}

Numbers
AngularJS numbers are similar to JavaScript numbers.
<!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="quantity=5;cost=5">
<p>Total in dollar: {{ quantity * cost }}</p>
</div>
</body>
</html>

We can use the same example by using ng-bind:

<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/an
gular.min.js"></script>
<body>
<div ng-app="" ng-init="quantity=5;cost=5">
<p>Total in dollar: <span ng-
bind="quantity * cost"></span></p>
</div>
</body>
</html>
Unit-4: Angular JS

Strings
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/an
gular.min.js"></script>
<body>
<div ng-app="" ng-init="firstName='Sonoo';lastName='Jaiswal'">
<p>My full name is: {{ firstName + " " + lastName }}</p>
</div>
</body>
</html>

Objects
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/an
gular.min.js"></script>
<body>
<div ng-app="" ng-
init="person={firstName:'Sonoo',lastName:'Jaiswal'}">
<p>My name is {{ person.firstName }}</p>
</div>
</body>
</html>

Arrays
<!DOCTYPE html>
<html>
Unit-4: Angular JS

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/an
gular.min.js"></script>
<body>
<div ng-app="" ng-init="points=[1,15,19,2,40]">
<p>The first result is {{ points[0] }}</p>
</div>
</body>
</html>

4.1.2 Setting up Environment, Angular JS Filters


Environment Setup
• First download the script file from https://angularjs.org/
• Click on Download AngularJS 1 image.

• You can download the AngularJS script file, when you click on download
button. You can download Minified, Uncompressed or in Zip file format.
• If you downloaded the zip file, then unzip it and copy and paste
angularjs.min.js file in your visual studio project folder.

Angular JS Filters
In AngularJS, filters are used to format data. Following is a list of filters used for
transforming data.

Filter Description

Currency It formats a number to a currency format.

Date It formats a date to a specified format.

Filter It select a subset of items from an array.

Json It formats an object to a Json string.


Unit-4: Angular JS

Limit It is used to limit an array/string, into a specified number of


elements/characters.

Lowercase It formats a string to lower case.

Number It formats a number to a string.

Orderby It orders an array by an expression.

Uppercase It formats a string to upper case.

How to add filters to expressions

• You can add filters to expressions by using the pipe character |, followed
by a filter.
• In this example, the uppercase filter format strings to upper case:

<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js
"></script>
<body>
<div ng-app="myApp" ng-controller="personCtrl">
<p>The name is {{ firstName | uppercase }}</p>
</div>
<script>
angular.module('myApp', []).controller('personCtrl', function($scope) {
$scope.firstName = "Sonoo",
$scope.lastName = "Jaiswal"
});
</script>
</body>
</html>

4.1 3 Understanding MVC (Model, View, Controller)


architecture
Unit-4: Angular JS

• MVC stands for Model View Controller.


• It is a software design pattern for developing web applications.
• It is very popular because it isolates the application logic from the user
interface layer and supports separation of concerns.

The MVC pattern is made up of the following three parts:

1. Model: It is responsible for managing application data. It responds to the


requests from view and to the instructions from controller to update
itself.
2. View: It is responsible for displaying all data or only a portion of data to
the 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.
3. Controller: It is responsible to control the relation between models and
views. It responds to user input and performs interactions on the data
Unit-4: Angular JS

model objects. The controller receives input, validates it, and then
performs business operations that modify the state of the data model.

4.2 AngularJS Directive (ng-app, ng-init, ng-controller, ng-


model, ng-repeat)
• AngularJS facilitates you to extend HTML with new attributes. These
attributes are called directives.
• There is a set of built-in directive in AngularJS which offers functionality
to your applications. You can also define your own directives.

ng-app
• ng-app directive defines the root element.
• It starts an AngularJS Application and 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.

<div ng-app = "">


...
</div>

ng-init
• ng-init directive initializes an AngularJS Application data. It defines the
initial values for an AngularJS application.
• In following example, we'll initialize an array of countries. We're using
JSON syntax to define array of countries.
Unit-4: Angular JS

<div ng-app = "" ng-init = "countries = [{locale:'en-


IND',name:'India'}, {locale:'en-PAK',name:'Pakistan'}, {locale:'en-
AUS',name:'Australia'}]">
...
</div>

ng-controller
• The AngularJS ng-controller directive adds a controller class to the view
(your application). It is the key aspect which specifies the principles
behind the Model-View-Controller design pattern.
• It facilitates you to write code and make functions and variables, which
will be parts of an object, available inside the current HTML element. This
object is called scope.
• This is supported by all HTML elements.
• Syntax <element ng-controller="expression"></element>

<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js
"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
Full Name: {{firstName + " " + lastName}}
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.firstName = "Aryan";
$scope.lastName = "Jaiswal";
});
</script>
Unit-4: Angular JS

<p>In this example you can see how to define a controller, and how to use vari
ables made for the scope.</p>
</body>
</html>

ng-model
• ng-model directive defines the model/variable to be used in AngularJS
Application.
• 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
• 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">
{{ 'Country: ' + country.name + ', Locale: ' + country.locale }}
</li>
</ol>
Unit-4: Angular JS

4.2.1 Some other directives: ng-class, ng-animate, ng-show,


ng-hide
ng-class
• The AngularJS ng-class directive facilitates you to dynamically set CSS
classes on an HTML element by databinding an expression that represents
all classes to be added.
• It may be a String, an object or an array.
• In case of a string, it should contain one or more, space-separated class
names.
• In case of an object, it should contain key-value pairs, where the key is the
class name of the class you want to add, and the value is a Boolean value.
• In the case of an array, it can be a combination of both.
• <element ng-class="expression"></element>
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js
"></script>
<style>
.normal {
color:white;
background-color:grey;
padding:20px;
font-family:"Courier New";
}
.medium {
color:white;
background-color:brown;
padding:30px;
font-family:"Courier New";
}
.advance {
background-color:red;
padding:40px;
Unit-4: Angular JS

font-family:Verdana;
}
</style>
<body ng-app="">
<p>Choose a class:</p>
<select ng-model="home">
<option value="normal">Normal</option>
<option value="medium">Medium</option>
<option value="advance">Advance</option>
</select>
<div ng-class="home">
<h1>Hello</h1>
<p>World</p>
</div>
</body>
</html>

ng-animate
• In angularjs ngAnimate module will provide a CSS based animation
transitions effect to elements while performing show/hide or fade in /
fade out, etc. events.
• In angularjs ngAnimate module will add/remove some pre-defined CSS
classes to HTML elements to provide animation effect whenever certain
events raised like show/hide elements.
<!DOCTYPE html>
<html>
<head>
<title>AngularJS Animations Example</title>
<script src="http://ajax.googleapis.com/ajax/libs/angular
js/1.4.8/angular.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angular
js/1.4.8/angular-animate.js"></script>
<script type="text/javascript">
var app = angular.module("angularapp", ["ngAnimate"]);
</script>
Unit-4: Angular JS

<style>
div
{
transition: all linear 0.5s;
background-color: #08c;
width: 30%;
padding:30px;
border:1px solid black;
}
.ng-hide {
opacity:0;
}
</style>
</head>
<body ng-app="angularapp">
<h2>AngularJS Animations Example</h2>
Show / Hide Div <input type="checkbox" ng-
model="chkselct"><br /><br />
<div ng-hide='chkselct' style="clear:both;">Hi Welcome to
Angularjs... Hello World</div>
</body>
</html>

The following are some of the directives that supports animation effect.

• ng-repeat
• ng-view
• ng-include
• ng-show / hide
• ng-switch
• ng-if
• Whenever ng-show / hide events raised ngAnimate module is used ng-
hide class to add/remove animation effect.

• The other directives use ng-enter and ng-leave classes to add/remove


the animation effect for HTML elements.

• This is how we can implement an animation effect to the elements in


angularjs applications using the ngAnimate module.
Unit-4: Angular JS

ng-show
• The AngularJS ng-show directive is used to show or hide the given HTML
element according to the expression given to the ng-show attribute.
• It shows the specified HTML element if the given expression is true,
otherwise it hides the HTML element.

<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js
"></script>
<body ng-app="">
Show HTML element: <input type="checkbox" ng-model="myVar">
<div ng-show="myVar">
<h1>Hello</h1>
<p>Class.</p>
</div>
</body>
</html>

ng-hide
• The AngularJS ng-hide directive is used to hide the HTML element if the
expression is set to true.
• The element is shown if you remove the ng-hide CSS class and hidden, if
you add the ng-hide CSS class onto the element. The ng-hide CSS class is
predefined in AngularJS and sets the element's display to none.
• <element ng-hide="expression"></element>

As a CSS class:

• <element class="ng-hide"></element>
<!DOCTYPE html>
<html>
Unit-4: Angular JS

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js
"></script>
<body ng-app="">
Hide HTML: <input type="checkbox" ng-model="myVar">
<div ng-hide="myVar">
<h1>Welcome </h1>
<p>A solution of all technologoes.</p>
</div>
</body>
</html>

4.2.2 Expressions and 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 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>

Here, we declare a controller named studentController, using the ng-


controller directive. We define it as follows –

<script>
function studentController($scope) {
$scope.student = {
firstName: "Mahesh",
lastName: "Parashar",

fullName: function() {
var studentObject;
Unit-4: Angular JS

studentObject = $scope.student;
return studentObject.firstName + " " + studentObject.lastName;
}
};
}
</script>
• The studentController is defined as a JavaScript object with $scope as
an argument.
• The $scope refers to application which uses the studentController
object.
• The $scope.student is a property of studentController object.
• The firstName and the lastName are two properties of $scope.student
object. We pass the default values to them.
• The property fullName is the function of $scope.student object, which
returns the combined name.
• In the fullName function, we get the student object and then return the
combined name.
• As a note, we can also define the controller object in a separate JS file
and refer that file in the HTML page.

Example:
<html>
<head>
<title>Angular JS Controller</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">


Enter first name: <input type = "text" ng-model = "student.firstName"><br>
<br>
Enter last name: <input type = "text" ng-model = "student.lastName"><br>
<br>
You are entering: {{student.fullName()}}
</div>

<script>
var mainApp = angular.module("mainApp", []);
Unit-4: Angular JS

mainApp.controller('studentController', function($scope) {
$scope.student = {
firstName: "Mahesh",
lastName: "Parashar",

fullName: function() {
var studentObject;
studentObject = $scope.student;
return studentObject.firstName + " " + studentObject.lastName;
}
};
});
</script>

</body>
</html>

4.2.3 Filters (Uppercase, Lowercase, Currency, order by)


Uppercase
The uppercase filter converts the string to upper case.
<!DOCTYPE html>
<html >
<head>
<script src="~/Scripts/angular.js"></script>
</head>
<body ng-app>
<div ng-
init="person.firstName='James';person.lastName='Bond'">
Upper case: {{person.firstName + ' ' + person.lastName |
uppercase}}
</div>
</body>
</html>

Lowercase
The lowercase filter converts the string to lower case.
Unit-4: Angular JS

<!DOCTYPE html>
<html >
<head>
<script src="~/Scripts/angular.js"></script>
</head>
<body ng-app>
<div ng-
init="person.firstName='James';person.lastName='Bond'">
Lower case: {{person.firstName + ' ' + person.lastName |
lowercase}} <br />
</div>
</body>
</html>

Currency
The currency filter formats a number value as a currency. When no currency
symbol is provided, default symbol for current locale is used.

{{ expression | currency : 'currency_symbol' : 'fraction'}}

<!DOCTYPE html>
<html >
<head>
<script src="~/Scripts/angular.js"></script>
</head>
<body ng-app="myApp">
<div ng-controller="myController">
Default currency: {{person.salary | currency}} <br />
Custom currency identifier: {{person.salary |
currency:'Rs.'}} <br />
No Fraction: {{person.salary | currency:'Rs.':0}} <br />
Fraction 2: <span ng-bind="person.salary|
currency:'GBP':2"></span>
</div>
<script>
var myApp = angular.module('myApp', []);

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


$scope.person = { firstName: 'James', lastName: 'Bond',
salary: 100000}
});
</script>
</body>
Unit-4: Angular JS

</html>

order by
• The orderBy filter sorts an array based on specified expression predicate.
• {{ expression | orderBy : predicate_expression : reverse}}

<!DOCTYPE html>
<html>
<head>
<script src="~/Scripts/angular.js"></script>
</head>
<body ng-app="myApp">
<div ng-controller="myController">
<select ng-model="SortOrder">
<option value="+name">Name (asc)</option>
<option value="-name">Name (dec)</option>
<option value="+phone">Phone (asc)</option>
<option value="-phone">Phone (dec)</option>
</select>
<ul ng-repeat="person in persons | orderBy:SortOrder">
<li>{{person.name}} - {{person.phone}}</li>
</ul>
</div>
<script>
var myApp = angular.module('myApp', []);

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

$scope.persons = [{ name: 'John', phone: '512-455-1276'


},
{ name: 'Mary', phone: '899-333-3345' },
{ name: 'Mike', phone: '511-444-4321' },
{ name: 'Bill', phone: '145-788-5678' },
{ name: 'Ram', phone: '433-444-8765' },
{ name: 'Steve', phone: '218-345-5678' }]

$scope.SortOrder = '+name';
});
</script>
</body>
</html>

You might also like