0% found this document useful (0 votes)
32 views19 pages

Unit 5

Uploaded by

bitestkaran
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)
32 views19 pages

Unit 5

Uploaded by

bitestkaran
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/ 19

Unit 5 : Angular JS: Single page application

Single page applications using Angular JS


Create a Module, Define Simple controller

A module in AngularJS is a container of the different parts of an application such as controller,


service, filters, directives, factories etc. It supports separation of concern using modules.

AngularJS stops polluting global scope by containing AngularJS specific functions in a module.

A module is used as a Main() method. Controller always belongs to a module.

An AngularJS application must create a top level application module. This application module can
contain other modules, controllers, filters, etc.

the angular.module() method creates an application module, where the first parameter is a module
name which is same as specified by ng-app directive.The second parameter is an array of other
dependent modules [].

The angular.module() method returns specified module object if no dependency is specified. Therefore,
specify an empty array even if the current module is not dependent on other module.

How to create a module

The angular object's module() method is used to create a module.

<div ng-app="myApp">...</div>
<script>
var app = angular.module("myApp", [ ]);
</script>
"myApp" specifies an HTML element in which the application will run.

the first parameter is a module name which is same as specified by ng-app directive. The second
parameter is an array of other dependent modules []. User can add other modules in the myApp
module.

we can create separate JavaScript files for each module

Angular Modules in Separate Files


<!DOCTYPE html>
<html >
<head>
<script src="~/Scripts/angular.js"></script>
</head>
<body ng-app="myApp">
<div ng-controller="myController">

Vivekanand College for BCA Page 1


Unit 5 : Angular JS: Single page application

{{message}}
</div>
<script src="app.js" ></script>
<script src="myController.js" ></script>
</body>
</html>
app.js
var myApp = angular.module("myApp", []);
myController.js

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


$scope.message = "Hello Angular World!";
});

Define Simple controller


A controller is defined using ng-controller directive. A controller is a JavaScript object containing
attributes/properties and functions. Each controller accepts $scope as a parameter which refers
to the application/module that controller is to control.

User can attach properties and methods to the $scope object inside a controller function,
which in turn will add/update the data and attach behaviours to HTML elements. The $scope
object is a connection between the controller and HTML.

How to add controller to a module

<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">
{{ firstName + " " + lastName }}
</div>
<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.firstName = "Sachin";
$scope.lastName = "Tendulkar";
});
</script>
</body>
</html>
Output :
Sachin Tendulkar

Vivekanand College for BCA Page 2


Unit 5 : Angular JS: Single page application

In the above example, ng-controller="myCtrl" directive is applied to the <div> element where
"myCtrl" is the name of the controller. To create "myCtrl", we need to create an application module.
The module defines an application and keeps its parts like controllers, services etc. out of global
scope. After creating a module, we add a controller function using the controller() method where the
first parameter should be the name of the controller and second parameter should be a function for
the controller. The controller function includes $scope parameter which will be injected by AngularJS
framework.

AngularJS controller example with methods (variables as functions)

<html>
<head>
<title>AngualrJS Controller</title>
<script src="~/Scripts/angular.js"></script>
</head>
<body ng-app="myNgApp">
<div id="div1" ng-controller="myController">
Message: {{message}} <br />
<div id="div2">
Message: {{message}}
</div>
</div>
<div id="div3">
Message: {{message}}
</div>
<div id="div4" ng-controller="anotherController">
Message: {{message}}
</div>
<script>
var ngApp = angular.module('myNgApp', []);

ngApp.controller('myController', function ($scope) {


$scope.message = "This is myController";
});

ngApp.controller('anotherController', function ($scope) {


$scope.message = "This is anotherController";
});
</script>
</body>
</html>
the "message" property is defined inside myController, so it will only be available to div1 and div2
but not div3 and div4. The same way, message property defined inside anotherController will only be
available to div4. The div3 element does not come under any controller, so "message" property will
be null or undefined.

Vivekanand College for BCA Page 3


Unit 5 : Angular JS: Single page application

Attach Complex object

<html>
<head>
<title>AngualrJS Controller</title>
<script src="~/Scripts/angular.js"></script>
</head>
<body ng-app="myNgApp">
<h2>Student Information:</h2>
<div ng-controller="myController">
First Name: {{student.firstName}} <br />
Last Name: {{student.lastName}}
</div>
<script>
var ngApp = angular.module('myNgApp', []);

ngApp.controller('myController', function ($scope) {


$scope.student = { firstName: 'James', lastName: 'Bond' };
});
</script>
</body>
</html>

Nested Controllers

<html>
<head>
<title>AngualrJS Controller</title>
<script src="~/Scripts/angular.js"></script>
</head>
<body ng-app="myNgApp">
<div ng-controller="parentController">
Message: {{message1}}

<div ng-controller="childController">
Parent Message: {{message1}} </br>
Child Message: {{message2}}
</div>

Child Message: {{message2}}


</div>

<script>
var ngApp = angular.module('myNgApp', []);

ngApp.controller('parentController', function ($scope) {

Vivekanand College for BCA Page 4


Unit 5 : Angular JS: Single page application

$scope.message1 = "This is parentController";


});

ngApp.controller('childController', function ($scope) {


$scope.message2 = "This is childController";
});
</script>
</body>
</html>

Attach Behaviors to controller

<html>
<head>
<title>AngualrJS Controller</title>
<script src="~/Scripts/angular.js"></script>
</head>
<body ng-app="myNgApp">
<div ng-controller="myController">
Enter Message: <input type="text" ng-model="message" /> <br />
<button ng-click="showMsg(message)">Show Message</button>
</div>
<script>
var ngApp = angular.module('myNgApp', []);

ngApp.controller('myController', function ($scope) {


$scope.message = "Hello World!";

$scope.showMsg = function (msg) {


alert(msg);
};
});
</script>
</body>
</html>

Embedding AngularJS script in HTML


 Create an app and its controller scope.
 Define the controller variable.
 Call the app and controller to the body of HTML.
 Inside the body use span tag and use attribute ng-bind-html and assign the value as the scope
variable.

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


<span ng-bind-html="message"></span>

Vivekanand College for BCA Page 5


Unit 5 : Angular JS: Single page application

<script type="text/javascript">
var app = angular.module('myApp', ['ngSanitize']);
app.controller('myCtrl', function($scope) {
$scope.message = '<h1>GeeksforGeeks</h1>';
});
</script>
</body>

<body ng-controller="geek" style="text-align: center">

<h1 style="color: green">GeeksforGeeks</h1>


<h3>Displaying HTML content value in AngularJS</h3>

<p ng-bind-html="text"></p>

<script>
var myApp = angular.module('myApp', ['ngSanitize']);
myApp.controller('geek', ['$scope',
function($scope) {
$scope.text = "<p class ='green'> GeeksforGeeks Learning Together</p>";
},
]);
</script>
</body>

AngularJS’s routing capability

 AngularJS supports SPA using routing module ngRoute. This routing module acts based on the url.
When a user requests a specific url, the routing engine captures that url and renders the view
based on the defined routing rules. Routing in AngularJS is used when the user wants to navigate
to different pages in an application but still wants it to be a single-page application. AngularJS
routes enable the user to create different URLs for different content in an application.
The ngRoute module helps in accessing different pages of an application without reloading the
entire application.
 $routeProvider is used to configure the routes. It helps to define what page to display when a user
clicks a link. It accepts either when() or otherwise() method.
 The ngRoute must be added as a dependency in the application module:

$routeProvider service from ngRoute

we need to configure the routing rules that need to compile before any other module of an application.
So, use config() method to configure the routing rules using $routingProvider object.

Vivekanand College for BCA Page 6


Unit 5 : Angular JS: Single page application

Use $routeProvider.when(path, route) method to configure routing rules, where the first parameter is
request URL and the second parameter is an object which contains controller, template, or other
properties.

Navigating different pages

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.

<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"})
.when("/blue", {templateUrl : "blue.htm"});
});
</script>
</body>

Application needs a container to put the content provided by the routing.

This container is the ng-view directive. With the $routeProvider you can define what page to display
when a user clicks a link.

With the $routeProvider you can also define a controller for each "view".

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


app.config(function($routeProvider) {
$routeProvider
.when("/", {
templateUrl : "main.htm"

Vivekanand College for BCA Page 7


Unit 5 : Angular JS: Single page application

})
.when("/london", {
templateUrl : "red.htm",
controller : "redCtrl"
})
.when("/paris", {
templateUrl : "yellow.htm",
controller : "yellowCtrl"
});
});
app.controller("redCtrl", function ($scope) {
$scope.msg = "Red color";
});
app.controller("yellowCtrl", function ($scope) {
$scope.msg = "Yellow color";
});

The otherwise method

we have used the when method of the $routeProvider.

You can also use the otherwise method, which is the default route when none of the others get a match.

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


app.config(function($routeProvider) {
$routeProvider
.when("/banana", {
template : "<h1>Banana</h1><p>Bananas contain around 75% water.</p>"
})
.when("/tomato", {
template : "<h1>Tomato</h1><p>Tomatoes contain around 95% water.</p>"
})
.otherwise({
template : "<h1>None</h1><p>Nothing has been selected</p>"
});
});

Vivekanand College for BCA Page 8


Unit 5 : Angular JS: Single page application

HTML DOM directives

In AngularJS, some directives can be used to bind application data to attributes of HTML DOM
elements.

These directives are:


Directive Description

ng-disabled It disables a given control.

ng-show It shows a given control.

ng-hide It hides a given control.

ng-click It represents an AangularJS click event.

5.2.1 ng-disabled, ng-show, ng-hide, ng-click

ng-disabled directive:The ng-disabled directive binds AngularJS application data to the disabled
attribute of HTML elements. In the below code, it binds a model to a checkbox.

<!DOCTYPE html>
<html>
<head>
<script src="~/Scripts/angular.js"></script>
<style>
div {
width: 100%;
height: 50px;
display: block;
margin: 15px 0 0 10px;
}
</style>
</head>
<body ng-app ng-init="checked=true" >
Click Me: <input type="checkbox" ng-model="checked" /> <br />
<div>
New: <input ng-if="checked" type="text" />
</div>
<div>
Read-only: <input ng-readonly="checked" type="text" value="This is read-only." />

Vivekanand College for BCA Page 9


Unit 5 : Angular JS: Single page application

</div>
<div>
Disabled: <input ng-disabled="checked" type="text" value="This is disabled." />
</div>
</body>
</html>
Try it

ng-show directive: The ng-show directive shows or hides an HTML element. In the below code,
it binds a model to a checkbox.

<input type = "checkbox" ng-model = "showHide1">Show Button


button ng-show = "showHide1">Click Me!</button>

ng-hide directive: The ng-hide directive hides or shows an HTML element. In the below code, it
binds a model to a checkbox.

<input type = "checkbox" ng-model = "showHide2">Hide Button


<button ng-hide = "showHide2">Click Me!</button>

ng-click directive: The ng-click directive counts the total clicks an HTML element. In the below
code, it binds a model to a checkbox.

<p>Total click: {{ clickCounter }}</p>


lt;button ng-click = "clickCounter = clickCounter + 1">Click Me!</button>

<!DOCTYPE html>
<html>
<head>
<title>AngularJS HTML DOM</title>
</head>
<body>
<h2>AngularJS Sample Application</h2>
<div ng-app = "">
<table border = "0">
<tr>
<td><input type = "checkbox" ng-model = "enableDisableButton">Disable Button</td>
<td><button ng-disabled = "enableDisableButton">Click Me!</button></td>
</tr>
<tr>
<td><input type = "checkbox" ng-model = "showHide1">Show Button</td>

Vivekanand College for BCA Page 10


Unit 5 : Angular JS: Single page application

<td><button ng-show = "showHide1">Click Me!</button></td>


</tr>
<tr>
<td><input type = "checkbox" ng-model = "showHide2">Hide Button</td>
<td><button ng-hide = "showHide2">Click Me!</button></td>
</tr>
<tr>
<td><p>Total click: {{ clickCounter }}</p></td>
<td><button ng-click = "clickCounter = clickCounter + 1">Click Me!</button></td>
</tr>
</t able>
</div>
<script src = "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
</body>
</html>

5.2.2 Modules ( Application, Controller )

A module in AngularJS is a container of the different parts of an application such as


controller, service, filters, directives, factories etc. It supports separation of concern using
modules.

AngularJS stops polluting global scope by containing AngularJS specific functions in a


module.

Application Module

An AngularJS application must create a top level application module. This application module
can contain other modules, controllers, filters, etc.

<!DOCTYPE html>
<html >
<head>
<script src="~/Scripts/angular.js"></script>
</head>
<body ng-app="myApp">
@* HTML content *@
<script>
var myApp = angular.module('myApp', []);

</script>

Vivekanand College for BCA Page 11


Unit 5 : Angular JS: Single page application

</body>
</html>
In the above example, the angular.module() method creates an application module, where
the first parameter is a module name which is same as specified by ng-app directive. The
second parameter is an array of other dependent modules []. In the above example we are
passing an empty array because there is no dependency.

Now, you can add other modules in the myApp module.

The following example demonstrates creating controller module in myApp module.

<!DOCTYPE html>
<html >
<head>
<script src="~/Scripts/angular.js"></script>
</head>
<body ng-app="myApp">
<div ng-controller="myController">
{{message}}
</div>
<script>
var myApp = angular.module("myApp", []);

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


$scope.message = "Hello Angular World!";
});
</script>
</body>
</html>

AngularJS Controller

The controller in AngularJS is a JavaScript function that maintains the application data and
behavior using $scope object.

You can attach properties and methods to the $scope object inside a controller function,
which in turn will add/update the data and attach behaviours to HTML elements. The $scope
object is a glue between the controller and HTML.

The ng-controller directive is used to specify a controller in HTML element, which will add
behavior or maintain the data in that HTML element and its child elements.

The following example demonstrates attaching properties to the $scope object inside a
controller and then displaying property value in HTML.

Vivekanand College for BCA Page 12


Unit 5 : Angular JS: Single page application

<!DOCTYPE html>
<html >
<head>
<title>AngualrJS Controller</title>
<script src="~/Scripts/angular.js"></script>
</head>
<body ng-app="myNgApp">
<div ng-controller="myController">
{{message}}
</div>
<script>
var ngApp = angular.module('myNgApp', []);

ngApp.controller('myController', function ($scope) {


$scope.message = "Hello World!";
});
</script>
</body>
</html>

5.2.3 Forms ( Events, Data validation, ng-click )

Input controls are ways for a user to enter data. A form is a collection of controls for the
purpose of grouping related controls together.

Following are the input controls used in AngularJS forms:

o input elements
o select elements
o button elements
o textarea elements

AngularJS provides multiple events that can be associated with the HTML controls. These
events are associated with the different HTML input elements.

Following is a list of events supported in AngularJS:

o ng-click
o ng-dbl-click
o ng-mousedown
o ng-mouseup

Vivekanand College for BCA Page 13


Unit 5 : Angular JS: Single page application

o ng-mouseenter
o ng-mouseleave
o ng-mousemove
o ng-mouseover
o ng-keydown
o ng-keyup
o ng-keypress
o ng-change

Data Binding

ng-model directive is used to provide data binding.

Let's take an example where ng-model directive binds the input controller to the rest of your
application

1. <!DOCTYPE html>
2. <html>
3. <head>
4. <title>Angular JS Forms</title>
5. <script src = "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script
>
6.
7. <style>
8. table, th , td {
9. border: 1px solid grey;
10. border-collapse: collapse;
11. padding: 5px;
12. }
13.
14. table tr:nth-child(odd) {
15. background-color: lightpink;
16. }
17.
18. table tr:nth-child(even) {
19. background-color: lightyellow;
20. }
21. </style>
22.
23. </head>

Vivekanand College for BCA Page 14


Unit 5 : Angular JS: Single page application

24. <body>
25.
26. <h2>AngularJS Sample Application</h2>
27. <div ng-app = "mainApp" ng-controller = "studentController">
28.
29. <form name = "studentForm" novalidate>
30. <table border = "0">
31. <tr>
32. <td>Enter first name:</td>
33. <td><input name = "firstname" type = "text" ng-model = "firstName" required>
34. <span style = "color:red" ng-
show = "studentForm.firstname.$dirty && studentForm.firstname.$invalid">
35. <span ng-
show = "studentForm.firstname.$error.required">First Name is required.</span>
36. </span>
37. </td>
38. </tr>
39.
40. <tr>
41. <td>Enter last name: </td>
42. <td><input name = "lastname" type = "text" ng-model = "lastName" required>
43. <span style = "color:red" ng-
show = "studentForm.lastname.$dirty && studentForm.lastname.$invalid">
44. <span ng-
show = "studentForm.lastname.$error.required">Last Name is required.</span>
45. </span>
46. </td>
47. </tr>
48.
49. <tr>
50. <td>Email: </td><td><input name = "email" type = "email" ng-
model = "email" length = "100" required>
51. <span style = "color:red" ng-
show = "studentForm.email.$dirty && studentForm.email.$invalid">
52. <span ng-
show = "studentForm.email.$error.required">Email is required.</span>
53. <span ng-
show = "studentForm.email.$error.email">Invalid email address.</span>
54. </span>
55. </td>
56. </tr>
57.
58. <tr>

Vivekanand College for BCA Page 15


Unit 5 : Angular JS: Single page application

59. <td>
60. <button ng-click = "reset()">Reset</button>
61. </td>
62. <td>
63. <button ng-disabled = "studentForm.firstname.$dirty &&
64. studentForm.firstname.$invalid || studentForm.lastname.$dirty &&
65. studentForm.lastname.$invalid || studentForm.email.$dirty &&
66. studentForm.email.$invalid" ng-click="submit()">Submit</button>
67. </td>
68. </tr>
69.
70. </table>
71. </form>
72. </div>
73.
74. <script>
75. var mainApp = angular.module("mainApp", []);
76.
77. mainApp.controller('studentController', function($scope) {
78. $scope.reset = function(){
79. $scope.firstName = "Sonoo";
80. $scope.lastName = "Jaiswal";
81. $scope.email = "[email protected]";
82. }
83.
84. $scope.reset();
85. });
86. </script>
87. </body>
88. </html>

AngularJS Form Validation

AngularJS provides client-side form validation. It checks the state of the form and input
fields (input, textarea, select), and lets you notify the user about the current state.

It also holds the information about whether the input fields have been touched, or
modified, or not.

Following directives are generally used to track errors in an AngularJS form:

Vivekanand College for BCA Page 16


Unit 5 : Angular JS: Single page application

o $dirty - states that value has been changed.


o $invalid - states that value entered is invalid.
o $error - states the exact error.

1. <!DOCTYPE html>
2. <html>
3. <head>
4. <title>Angular JS Forms</title>
5. <script src = "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></scrip
t>
6.
7. <style>
8. table, th , td {
9. border: 1px solid grey;
10. border-collapse: collapse;
11. padding: 5px;
12. }
13.
14. table tr:nth-child(odd) {
15. background-color: lightpink;
16. }
17.
18. table tr:nth-child(even) {
19. background-color: lightyellow;
20. }
21. </style>
22.
23. </head>
24. <body>
25.
26. <h2>AngularJS Sample Application</h2>
27. <div ng-app = "mainApp" ng-controller = "studentController">
28.
29. <form name = "studentForm" novalidate>
30. <table border = "0">
31. <tr>
32. <td>Enter first name:</td>
33. <td><input name = "firstname" type = "text" ng-model = "firstName" required>
34. <span style = "color:red" ng-
show = "studentForm.firstname.$dirty && studentForm.firstname.$invalid">
35. <span ng-
show = "studentForm.firstname.$error.required">First Name is required.</span>

Vivekanand College for BCA Page 17


Unit 5 : Angular JS: Single page application

36. </span>
37. </td>
38. </tr>
39.
40. <tr>
41. <td>Enter last name: </td>
42. <td><input name = "lastname" type = "text" ng-model = "lastName" required>
43. <span style = "color:red" ng-
show = "studentForm.lastname.$dirty && studentForm.lastname.$invalid">
44. <span ng-
show = "studentForm.lastname.$error.required">Last Name is required.</span>
45. </span>
46. </td>
47. </tr>
48.
49. <tr>
50. <td>Email: </td><td><input name = "email" type = "email" ng-
model = "email" length = "100" required>
51. <span style = "color:red" ng-
show = "studentForm.email.$dirty && studentForm.email.$invalid">
52. <span ng-
show = "studentForm.email.$error.required">Email is required.</span>
53. <span ng-
show = "studentForm.email.$error.email">Invalid email address.</span>
54. </span>
55. </td>
56. </tr>
57. <tr>
58. <td>
59. <button ng-click = "reset()">Reset</button>
60. </td>
61. <td>
62. <button ng-disabled = "studentForm.firstname.$dirty &&
63. studentForm.firstname.$invalid || studentForm.lastname.$dirty &&
64. studentForm.lastname.$invalid || studentForm.email.$dirty &&
65. studentForm.email.$invalid" ng-click="submit()">Submit</button>
66. </td>
67. </tr>
68. </table>
69. </form>
70. </div>
71. <script>
72. var mainApp = angular.module("mainApp", []);

Vivekanand College for BCA Page 18


Unit 5 : Angular JS: Single page application

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


74. $scope.reset = function(){
75. $scope.firstName = "Sonoo";
76. $scope.lastName = "Jaiswal";
77. $scope.email = "[email protected]";
78. }
79. $scope.reset();
80. });
81. </script>
82. </body>
83. </html>

Vivekanand College for BCA Page 19

You might also like