Module 5 AngularJs
Module 5 AngularJs
INTRODUCTION TO Angular JS
• AngularJS applications are a mix of HTML and JavaScript. The first thing you need
is an HTML page.
<!DOCTYPE html>
<html>
<head>
.
.
</head>
<body>
.
.
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<script src="[Link]
></script>
</head>
<body>
.
.
</body>
</html>
Example:
<!DOCTYPE html>
<html>
<script src="[Link]
[Link]"></script>
<body>
<div ng-app="">
<p>Name: <input type="text" ng-model="name"></p>
<p ng-bind="name"></p>
</div>
</body>
</html>
• The ng-app directive tells AngularJS that the <div> element is the "owner" of an
AngularJS application.
• The ng-model directive binds the value of the input field to the application variable name.
• The ng-bind directive binds the content of the <p> element to the application
variable name.
ng-app directive
• ng-app directive defines the root element.
• It is also used to load various AngularJS modules in AngularJS Application.
• The ng-app directive also tells AngularJS that the <div> element is the "owner" of the
AngularJS application.
• Example 1:
<!DOCTYPE html>
<html>
<script
src="[Link]
<body>
<div ng-app="" ng-init="firstName='abhi'">
<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>
Data Binding
• In this example two text fields are bound together with two ng-model directives:
<!DOCTYPE html>
<html>
<script
src="[Link]
<body>
<div ng-app="" ng-init="names=['','Mahesh','Abhi']">
<p>Looping with ng-repeat:</p>
<ul>
<li ng-repeat="x in names">
{{ x }}
</li>
</ul>
</div>
</body>
</html>
•
• Mahesh
• Abhi
AngularJS Expressions
• In AngularJS, expressions are used to bind application data to HTML.
• AngularJS expressions are written inside double braces: {{ expression }}.
• AngularJS expressions can also be written inside a directive: ng-bind="expression".
• AngularJS expressions are much like JavaScript expressions: They can contain literals,
operators, and variables.
Example:
<!DOCTYPE html>
<html>
<script
src="[Link]
<body>
<div ng-app="">
<p>My first expression: {{ 6 + 5 }}</p>
</div>
</body>
</html>
OUTPUT:
My first expression: 11
• Like JavaScript expressions, AngularJS expressions can contain literals, operators, and
variables.
• Unlike JavaScript expressions, AngularJS expressions can be written inside HTML.
• AngularJS expressions do not support conditionals, loops, and exceptions, while
JavaScript expressions do.
• AngularJS expressions support filters, while JavaScript expressions do not.
Creating a Module
Example:
<div ng-app="myApp">...</div>
<script>
var app = [Link]("myApp", []);
</script>
❖ The "myApp" parameter refers to an HTML element in which the application will run.
❖ Now you can add controllers, directives, filters, and more, to your AngularJS application.
Meaning
Example:
<!DOCTYPE html>
<html >
<head>
<script src="~/Scripts/[Link]"></script>
</head>
<body ng-app="myApp">
@* HTML content *@
<script>
var myApp = [Link]('myApp', []);
</script>
</body>
</html>
Explanation:
❖ In the above example, we have created a controller named "myController" using
[Link]() method.
❖ Here, myApp is an object of a module, and controller() method creates a controller inside
"myApp" module.
In the above example, we created application module and controller in the same HTML file. However, we can
create separate JavaScript files for each module as shown below.
Example:
<!DOCTYPE html>
<html >
<head>
<script src="~/Scripts/[Link]"></script>
</head>
<body ng-app="myApp">
<div ng-controller="myController">
{{message}}
</div>
<script src="[Link]" ></script>
<script src="[Link]" ></script>
</body>
</html>
[Link]
var myApp = [Link]("myApp", []);
[Link]
[Link]("myController", function ($scope) {
$[Link] = "Hello Welcome to MCA Department!";
});
Example:
<script type="text/javascript">
var app = [Link]('angularscopeapp', []);
[Link]('angularctrl', function ($scope) {
$[Link] = "Welcome to";
$[Link] = "JCEMCA";
});
</script>
<div ng-app="angularscopeapp" ng-controller="angularctrl">
First Name: {{fname}}<br />
Last Name: {{lname}}<br />
Full Name: <b>{{fname +" "+ lname}}</b>
</div>
Explanation of AngularJS Scope Syntax
• In above example we are defining controller in angularjs we are sending $scope object as an
argument and assigned parameters (fname, lname) to $scope object.
• Once we add properties to $scope object in controller we will get access to use those properties in
view (HTML).
• In view we can access those $scope properties by defining like {{fname}} we don’t need to prefix
with $scope.
<!DOCTYPE html>
<html >
<head>
<title>AngualrJS Controller</title>
<script src="~/Scripts/[Link]"></script>
</head>
<body ng-app="myNgApp">
<div ng-controller="myController">
{{message}}
</div>
<script>
var ngApp = [Link]('myNgApp', []);
Result:
Hello World!
❖ In the above example, ng-controller="myController" directive is applied to the <div> element
where "myController" is the name of the controller. Inside div element, we have specified
{{message}} expression.
❖ The $ sign is used as prefix in all the built-in objects in AngularJS, so that we can differentiate
AngularJS built-in objects and other objects.
❖ Now, to create "myController", we need to create an application module. The module defines an
application and keeps its parts like controllers, services etc. out of global scope. (You will learn
about the module in the next section.) After creating a module, we add a controller function using
the controller() method where the first parameter should be the name of the controller and second
parameter should be a function for the controller. The controller function includes $scope
parameter which will be injected by AngularJS framework.
Example
<!DOCTYPE html>
<html>
<script
src="[Link]
<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>
<script>
var app = [Link]('myApp', []);
[Link]('myCtrl', function($scope) {
$[Link] = "";
$[Link] = "xyz";
});
</script>
</body>
</html>
Application explained:
❖ 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).
AngularJS Filters
• Filters can be added in AngularJS to format data.
• AngularJS provides filters to transform data:
• currency: Format a number to a currency format.
• date: Format a date to a specified format.
• filter: Select a subset of items from an array.
• json: Format an object to a JSON string.
• limitTo: Limits an array/string, into a specified number of elements/characters.
• lowercase: Format a string to lower case.
• number: Format a number to a string.
• orderBy: Orders an array by an expression.
• uppercase: Format a string to upper case.
Adding Filters to Expressions
• Filters can be added to expressions by using the pipe character |, followed by a filter.
Example
<!DOCTYPE html>
<html>
<script
src="[Link]
<body>
<div ng-app="myApp" ng-controller="personCtrl">
<p>The name is {{ lastName | uppercase }}</p>
</div>
<script>
[Link]('myApp', []).controller('personCtrl', function($scope) {
$[Link] = "",
$[Link] = "xyz"
});
</script>
</body>
</html>
</div>
Filters are added to directives, like ng-repeat, by using the pipe character |, followed by a filter:
Example
<!DOCTYPE html>
<html>
<script src="[Link]
<body>
<div ng-app="myApp" ng-controller="namesCtrl">
<p>Looping with objects:</p>
<ul>
<li ng-repeat="x in names | orderBy:'department'">
{{ [Link] + ', ' + [Link] }}
</li>
</ul>
</div>
<script>
[Link]('myApp', []).controller('namesCtrl', function($scope) {
$[Link] = [
{name:'',department:'MCA'},
{name:'Harish',department:'CS'},
{name:'Rajesh',department:'Mechanical'},
{name:'Mahesh',department:'civil'},];
});
</script>
</body>
</html>
OUTPUT:
• Mahesh, civil
• Harish, CS
• , MCA
• Rajesh, Mechanical
❖ The filter Filter can only be used on arrays because it selects a subset of an array.
❖ It returns an array containing only the matching items.
❖ This example will return the names that contain the letter "o".
Example:
<!DOCTYPE html>
<html>
<script src="[Link]
<body>
<div ng-app="myApp" ng-controller="namesCtrl">
<ul>
<li ng-repeat="x in names | filter : 'o'">
{{ x }}
</li>
</ul>
</div>
<script>
[Link]('myApp', []).controller('namesCtrl', function($scope) {
$[Link] = [
'', 'Roopa',
'Rajesh',
'Mahesh',
'John',
'Santosh',
'Satish',
];
});
</script>
<p>This example displays only the names containing the letter "o".</p>
</body>
</html>
OUTPUT:
Roopa
John
Santosh
• AngularJS has about 30 built-in services. One of them is the $location service.
•The $location service has methods which return information about the location of the
current web page:
Example
Example:
Example
AngularJS Events
• AngularJS has its own HTML events directives.
• You can add AngularJS event listeners to your HTML elements by using one or more of
these directives:
• ng-blur
• ng-change
• ng-click
• ng-copy
• ng-cut
• ng-dblclick
• ng-focus
• ng-keydown
• ng-keypress
• ng-keyup
• ng-mousedown
• ng-mouseenter
• ng-mouseleave
• ng-mousemove
• ng-mouseover
• ng-mouseup
• ng-paste
Mouse Events
1. ng-mouseover
2. ng-mouseenter
3. ng-mousemove
4. ng-mouseleave
1. ng-mousedown
2. ng-mouseup
3. ng-click
Example
Increase the count variable when the mouse moves over the h1 element:
<!DOCTYPE html>
<html>
<script src="[Link]
<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 = [Link]('myApp', []);
[Link]('myCtrl', function($scope) {
$[Link] = 0;
});
</script>
</body>
</html>
Example
<div ng-app="myApp" ng-controller="myCtrl">
<button ng-click="count = count + 1">Click me!</button>
<p>{{ count }}</p>
</div>
<script>
var app = [Link]('myApp', []);
[Link]('myCtrl', function($scope) {
$[Link] = 0;
});
</script>
Toggle, True/False
If you want to show a section of HTML code when a button is clicked, and hide when the button
is clicked again, like a dropdown menu, make the button behave like a toggle switch:
<!DOCTYPE html>
<html>
<script src="[Link]
<body>
</body>
</html>
Input Controls
• input elements
• select elements
• button elements
• textarea elements
Checkbox
A checkbox has the value true or false. Apply the ng-model directive to a checkbox, and use its
value in your application.
Example:
<!DOCTYPE html>
<html>
<script src="[Link]
<body>
<div ng-app="">
<form>
Check to show a header:
<input type="checkbox" ng-model="myVar">
</form>
<h1 ng-show="myVar">My Header</h1>
</div>
<p>The header's ng-show attribute is set to true when the checkbox is checked.</p>
</body>
</html>
❖ Radio buttons with the same ng-model can have different values, but only the selected one
will be used.
Example
<!DOCTYPE html>
<html>
<script src="[Link]
<body ng-app="">
<form>
Pick a topic:
<input type="radio" ng-model="myVar" value="HTML">HTML
<input type="radio" ng-model="myVar" value="Javascript">Javascript
<input type="radio" ng-model="myVar" value="PHP">PHP
</form>
<div ng-switch="myVar">
<div ng-switch-when="HTML">
<h1>HTML</h1>
<p>Welcome to a world of [Link] is web progamming language</p>
</div>
<div ng-switch-when="Javascript">
<h1>Javascript</h1>
<p>This is client-side scripting language.</p>
</div>
<div ng-switch-when="PHP">
<h1>PHP</h1>
<p>This is server-side scripting language.</p>
</div>
</div>
<p><b>The ng-switch directive hides and shows HTML sections depending on the value of the
radio buttons.</b></p>
</body>
</html>
❖ Example to implement validation in the student form which contains First Name, Last Name and Email fields.
<!DOCTYPE html>
<html>
<head>
<script src="~/Scripts/[Link]"></script>
</head>
<body ng-app >
<form name="studentForm" novalidate>
<label for="firstName">First Name: </label> <br />
<input type="text" name="firstName" ng-model="[Link]" ng-required="true" />
<span ng-show="[Link].$touched && [Link].$[Link]">First name is
required.</span><br /><br />
<label for="lastName">Last Name</label><br />
<input type="text" name="lastName" ng-minlength="3" ng-maxlength="10" ng-model="[Link]" />
<span ng-show="[Link].$touched && [Link].$[Link]">min 3
chars.</span>
<span ng-show="[Link].$touched && [Link].$[Link]">Max 10
chars.</span><br /><br />
<label for="dob">Email</label><br />
<input type="email" id="email" ng-model="[Link]" name="email" />
<span ng-show="[Link].$touched && [Link].$[Link]">Please enter valid
email id.</span><br /><br />
<input type="submit" value="Submit" />
</form>
</body>
</html>
1. Apply novalidate attribute in <form> tag. The novalidate attribute will disable the browser's default
validation.
2. Set the name attribute in <form> and other elements, which will be used to obtain a reference of the
elements.
3. Now, set ng-required="true" on the input element of First Name. Also, set name attribute to the name of
model property, "firstName" in this case.
4. Create <span> element to specify an error message with every input filed where the validation directive is
applied.
5. Set ng-show directives to <span> element to an expression "[Link].$touched &&
[Link].$[Link]". This expression will return true if a user tabbed out without
entering FirstName.
6. The same way set ng-minlength & ng-maxlength directives to last name. Also, set ng-show directive to
"[Link].$touched && [Link].$[Link]" expression to <span>
element adjacent to LastName input field.
7. Create another <span> for maxlength validation message.
8. Email will be validated automatically with input type=email. Also, create <span> for email validation
message.
State Properties
❖ Angular includes properties which return the state of form and input controls.
❖ The state of the form and control changes based on the user's interaction and validation errors. These built-
in properties can be accessed using form name or input control name.
❖ To check the form status use [Link], and to check the state of input control,
use [Link].
❖ AngularJS is constantly updating the state of both the form and the input fields.
❖ Input fields have the following states:
They are all properties of the input field, and are either true or false.
They are all properties of the form, and are either true or false.
<h2>Validation Example</h2>
<p>Username:<br>
<input type="text" name="user" ng-model="user" required>
<span style="color:red" ng-show="[Link].$dirty && [Link].$invalid">
<span ng-show="[Link].$[Link]">Username is required.</span>
</span>
</p>
<p>Email:<br>
<input type="email" name="email" ng-model="email" required>
<span style="color:red" ng-show="[Link].$dirty && [Link].$invalid">
<span ng-show="[Link].$[Link]">Email is required.</span>
<span ng-show="[Link].$[Link]">Invalid email address.</span>
</span>
</p>
<p>
<input type="submit"
ng-disabled="[Link].$dirty && [Link].$invalid ||
[Link].$dirty && [Link].$invalid">
</p>
</form>
<script>
var app = [Link]('myApp', []);
[Link]('validateCtrl', function($scope) {
$[Link] = '';
$[Link] = '.ad@[Link]';
});
</script>
</body>
</html>
Example Explained
❖ The AngularJS directive ng-model binds the input elements to the model.
❖ Because of ng-show, the spans with color:red are displayed only when user or email is $dirty and $invalid.