Download as pdf or txt
Download as pdf or txt
You are on page 1of 21

Unit-5: Angular JS: Single page application

5.1 Single page application using AngularJS


5.1.1 Create a module, Define Simple controller
• The AngularJS module defines the functionality of the application which
is applied on the entire HTML page.
• It helps to link many components. So, it is just a group of related
components.
• It is a container which consists of different parts like controllers, services,
directives.
Note: This module should be made in a normal HTML file like index.html and
no need to create a new project in Visual Studio for this section.

How to create a Module:

var app = angular.module("Module-name", []);


In this [] we can add a list of components needed

<div ng-app = "module-name">


The code in which the module is required.
</div>

Adding a Controller:

app.controller("Controller-name", function($scope) {
$scope.variable-name= "";
});
Here, we can add any number of variables in controller and use them in the
html files, body of the tag in which the controller is added to that tag by
writing:
<body>
<div ng-app="Module-name">
<div ng-controller="Controller-name">
{{variable-name}}
</div>
Unit-5: Angular JS: Single page application

<!-- This wont get printed since its


not part of the div in which
controller is included -->
{{variable-name}}
</div>
</body>

Example:
DemoComponent.js
app.controller('DemoController', function($scope) {

$scope.list = ['A', 'E', 'I', 'O', 'U'];


$scope.choice = 'Your choice is: ';

$scope.ch = function(choice) {
$scope.choice = "Your choice is: " + choice;
};

$scope.c = function() {
$scope.choice = "Your choice is: " + $scope.mychoice;
};
});

Module-name: DemoApp.js
var app = angular.module('DemoApp', []);
index.html file
<!DOCTYPE html>
<html>

<head>
<title>
Modules and Controllers in Files
</title>
</head>

<body ng-app="DemoApp">
<h1>
Using controllers in Module
</h1>

<script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js
">
Unit-5: Angular JS: Single page application
</script>

<script src="DemoApp.js"></script>
<script src="DemoController"></script>

<div ng-app="DemoApp" ng-controller="DemoController">


Vowels List : <button ng-click="ch('A')" >A</button>

<button ng-click="ch('E')" >E</button>


<button ng-click="ch('I')" >I</button>
<button ng-click="ch('O')" >O</button>
<button ng-click="ch('U')" >U</button>

<p>{{ choice }}</p>

Vowels List :
<select ng-options="option for option in list"
ng-model="mychoice" ng-change="c()">
</select>

<p>{{ choice }}</p>


</div>
</body>

</html>

5.1.2 Embedding AngularJS script in HTML


• Angular provides the function to include the functionality from other
AngularJS files by using the ng-include directive.

• The primary purpose of the “ng-include directive” is used to fetch,


compile and include an external HTML fragment in the main AngularJS
application.

Step 1)

• Write the below code in a file called Table.html. This is the file which will
be injected into our main application file using the ng-include directive.

• The below code snippet assumes that there is a scope variable called
“tutorial.” It then uses the ng-repeat directive, which goes through each
Unit-5: Angular JS: Single page application
topic in the “Tutorial” variable and displays the values for the ‘name’ and
‘description’ key-value pair.

<table>
<tr ng-repeat="Topic in tutorial">
<td>{{ Topic.Name }}</td>
<td>{{ Topic.Country }}</td>
</tr>
</table>

Step 2)

• let’s write the below code in a file called Main.html. This is a simple
angular.JS application which has the following aspects

1. Use the “ng-include directive” to inject the code in the external file
‘Table.html’. The statement has been highlighted in bold in the below
code. So the div tag ‘ <div ng-include=”‘Table.html'”></div>’ will be
replaced by the entire code in the ‘Table.html’ file.
2. In the controller, a “tutorial” variable is created as part of the $scope
object. This variable contains a list of key-value pairs.

In our example, the key value pairs are

1. Name – This denotes the name of a topic such as Controllers, Models,


and Directives.
2. Description – This gives a description of each topic

The tutorial variable is also accessed in the ‘Table.html’ file.

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Event Registration</title>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js">
</script>
</head>
Unit-5: Angular JS: Single page application
<body ng-app="sampleApp">
<div ng-controller="AngularController">
<h3> Global Event</h3>
<div ng-include="'Table.html'"></div>
</div>
<script>

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


sampleApp.controller('AngularController', function($scope) {
$scope.tutorial =[
{Name: "Controllers" , Description : "Controllers in action"},
{Name: "Models" , Description : "Models and binding data"},
{Name: "Directives" , Description : "Flexibility of Directives"}
];

});
</script>
</body>
</html>

5.1.3 AngularJS’s routine capability


• Routing in AngularJS is one of the core feature. In this AngularJS routing
example, we will build a small single page application with multiple views
to show you how routing in AngularJS works.

ngRoute

• AngularJS ngRoute module provides routing, deep linking services and


directives for angular applications.

• We have to download angular-route.js script that contains the ngRoute


module from AngularJS official website to use the routing feature.

• You can also use the CDN in your application to include this file. In this
tutorial, We are going to use the Google
CDN. https://ajax.googleapis.com/ajax/libs/angularjs/1.2.28//angular-
route.min.js If you are bundling this file into your application, then you
can add it to your page with below code.
Unit-5: Angular JS: Single page application
<script src="angular-route.js">

If you want to include it from Google CDN, then use below code.

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

Then load the ngRoute module in your AngularJS application by adding it as a


dependent module as shown below.

angular.module('appName', ['ngRoute']);

ngView

• ngView directive is used to display the HTML templates or views in the


specified routes.

• Every time the current route changes, the included view changes with it
according to the configuration of the $route service.

$routeProvider

• $routeProvider is used to configure the routes.

• We use the ngRoute config() to configure the $routeProvider.

• The config() takes a function which takes the $routeProvider as


parameter and the routing configuration goes inside the function.
$routeProvider has a simple API, accepting either
the when() or otherwise() method.

AngularJS Routing Syntax

The following syntax is used to configure the routes in AngularJS.

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

app.config(function($routeProvider) {

$routeProvider

.when('/view1', {

templateUrl: 'view1.html',
Unit-5: Angular JS: Single page application
controller: 'FirstController'

})

.when('/view2', {

templateUrl: 'view2.html',

controller: 'SecondController'

})

.otherwise({

redirectTo: '/view1'

});

});

• when() method takes a path and a route as parameters.

• path is a part of the URL after the # symbol. route contains two properties
- templateUrl and controller.

• templateUrl property defines which HTML template AngularJS should


load and display inside the div with the ngView directive.

• controller property defines which controllers should be used with the


HTML template. When the application is loaded, path is matched against
the part of the URL after the # symbol.

• If no route paths matches the given URL the browser will be redirected to
the path specified in the otherwise() function.

AngularJS Routing Example

Now let’s go through a simple example to understand the AngularJS rounting.


At first, we will define a module, some routes, create controllers and create
multiple views. Finally, we will create the shell page of our application to hold
the multiple views.

1. Create a module named mainApp and load ngRoute as a dependent


module.
2. Configure the routes using $routeProvider.
Unit-5: Angular JS: Single page application
3. We use two paths in the example, /home and /viewStudents.
4. We use only a single controller in this example, StudentController
5. StudentController is initialized with an array of students and a message.
We will be showing the message in the home page and the students list
in viewStudents page.
6. Save this file as main.js

main.js

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

mainApp.config(function($routeProvider) {

$routeProvider

.when('/home', {

templateUrl: 'home.html',

controller: 'StudentController'

})

.when('/viewStudents', {

templateUrl: 'viewStudents.html',

controller: 'StudentController'

})

.otherwise({

redirectTo: '/home'

});

});

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

$scope.students = [
Unit-5: Angular JS: Single page application
{name: 'Mark Waugh', city:'New York'},

{name: 'Steve Jonathan', city:'London'},

{name: 'John Marcus', city:'Paris'}

];

$scope.message = "Click on the hyper link to view the students list.";

});

• For example, if the URL is


like https://www.journaldev.com/index.html#/home, The URL part after
the # matches /home, it will load home.html page and if it
matches /viewStudents then it will load viewStudents.html in to the shell
page.

• If nothing matches then it will go in otherwise condition and page will be


redirected to home.html. Now we can create our views and save
as home.html and viewStudents.html files. home.html

<div class="container">

<h2> Welcome </h2>

<p>{{message}}</p>

<a href="#/viewStudents"> View Students List</a>

</div>

This is the default page of our application. In this view, we just print out the
message, which we have already initialized in the StudentController. You can
also see a link to the viewStudents page. viewStudents.html

<div class="container">

<h2> View Students </h2>

Search:

<br/>
Unit-5: Angular JS: Single page application
<input type="text" ng-model="name" />

<br/>

<ul>

<li ng-repeat="student in students |


filter:name">{{student.name}} , {{student.city}}</li>

</ul>

<a href="#/home"> Back</a>

</div>

In the above view, you can see a list of students with a search option. Finally,
follow below steps to complete our AngularJS routing example application.

• ng-app auto-bootstraps our application mainApp


• ngView directive is the placeholder of the views
- home.html and viewStudents.html
• Include angular.min.js and angular-route.min.js
• Include main.js which we have created in the earlier steps.
• Save the file as index.html

index.html

<!DOCTYPE html>

<html>

<head lang="en">

<meta charset="utf-8">

<title>AngularJS Routing</title>

</head>

<body>
Unit-5: Angular JS: Single page application
<div ng-app="mainApp">

<ng-view></ng-view>

</div>

<script type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.28/angular.min.js"></
script>

<script type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.28//angular-
route.min.js"></script>

<script type="text/javascript" src="main.js"></script>

</body>

</html>

That’s all for our AngularJS Routing example. Our application is ready to run.

Run your application

• Save all the files in the same directory.


• open index.html from your browser

5.1.3.2 Navigating different pages


5.2 HTML DOM directives4
• The logical structure of documents and documents are accessed and
manipulated are defined using DOM elements.

• It defines events, methods, properties for all HTML elements as objects.


DOM in AngularJS acts as an API (programming interface) for javascript.

• Whenever a web page is loaded, the browser creates a Document Model


Object (DOM) of that page.
Unit-5: Angular JS: Single page application
A programmer can use DOM in AngularJS for the following purposes:

• Documents are built using DOM elements.


• A Programmer can navigate documents structure with DOM
elements.
• A programmer can add elements and content with DOM elements.
• Programmer can modify elements and content with DOM elements.

We can use various directives to bind the application data to the attributes of
DOM elements. Some of them are:
• ng-disabled
• ng-hide
• ng-click
• ng-show

5.2.1
ng-disabled
• We can use ng-disabled for disabling a given control. Attributes of HTML
elements can be disabled using ng-disabled directive.

• We can use it by adding it to an HTML button and pass it to model

Syntax
<input type = "checkbox" ng-model = "enableDisableButton">To disable a
button
<button ng-disabled = "enableDisableButton">Click</button>

Example
<!DOCTYPE html>
<html>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"
></script>
<body>
<div ng-app="" ng-init="value=true">
<p><button ng-disabled="value">Click Here!!</button></p>
<p><input type="checkbox" ng-model="value"/>Button</p>
<p>{{ value }}</p>
Unit-5: Angular JS: Single page application
</div>
</body>
</html>

• The ng-model directive binds the value of the HTML checkbox element to
the value of value (In the above code value is the name of application
data).

• If the value of value evaluates to true, the button will disable and if the
value of value evaluates to false, the button will not disable

ng-show
• We can use ng-show for showing a given control.

• We can use it by adding it to an HTML button and pass it to model

Syntax
<input type = "checkbox" ng-model = "showHide1">To show a Button
<button ng-show = "showHide1">Click </button>

Example
<!DOCTYPE html>
<html>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"
></script>
<body>
<div ng-app="">
<input type = "checkbox" ng-model = "showhiddenbutton">Show button
<button ng-show = "showhiddenbutton">Click Here!</button>
</div>
</body>
</html>
Unit-5: Angular JS: Single page application
• When the checkbox is checked the output displays a button of click
here! also.

Output-
(checked) Show button Click Here!

ng-hide
• We can use ng-hide for hiding a given control.

• We can use it by adding it to an HTML button and pass it to model

Syntax
<input type = "checkbox" ng-model = "showHide2">To hide a Button
<button ng-hide = "showHide2">Click</button>

Example
<!DOCTYPE html>
<html>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"
></script>
<div ng-app="">
<input type = "checkbox" ng-model = "hidebutton">Hide Button
<button ng-hide = "hidebutton">Click Here!</button>
</div>
</body>
</html>

Output-
__ Hide Button Click Here!

When you checked the checkbox, the button click here! will get hidden.

ng-click
Unit-5: Angular JS: Single page application
• We can use ng-click for representing an angularjs click event.

• We can use it by adding it to an HTML button and pass it to model

Syntax
<p>Number of click: {{ clickCounter }}</p>
<button ng-click = "clickCounter = clickCounter + 1">Click </button>

Example
<!DOCTYPE html>
<html>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"
></script>
<div ng-app="">
<p>Total number of Clicks: {{ Counts }}</p>
<button ng-click = "Counts = Counts+ 1">Click Here!</button>
</div>
</body>
</html>

• The number of times you will click on the button Click Here! will get
displayed corresponding to the total number of clicks.

5.2.2 Modules (Application, Controller)


5.2.3 Forms (Events, Data validation, ng-click)
AngularJS facilitates you to create a form enriches with data binding and
validation of input controls.

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
Unit-5: Angular JS: Single page application
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
o ng-mouseenter
o ng-mouseleave
o ng-mousemove
o ng-mouseover
o ng-keydown
o ng-keyup
o ng-keypress
o ng-change

Example:

<!DOCTYPE html>
<html>
<head>
<title>Angular JS Forms</title>
<script src = "http://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;
}
Unit-5: Angular JS: Single page application
table tr:nth-child(odd) {
background-color: lightpink;
}

table tr:nth-child(even) {
background-color: lightyellow;
}
</style>

</head>
<body>

<h2>AngularJS Sample Application</h2>


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

<form name = "studentForm" novalidate>


<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.$inv
alid">
<span ng-
show = "studentForm.firstname.$error.required">First Name is require
d.</span>
</span>
</td>
</tr>

<tr>
<td>Enter last name: </td>
<td><input name = "lastname" type = "text" ng-
model = "lastName" required>
Unit-5: Angular JS: Single page application
<span style = "color:red" ng-
show = "studentForm.lastname.$dirty && studentForm.lastname.$inva
lid">
<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" n
g-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.</spa
n>
</span>
</td>
</tr>

<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.$dir
ty &&
studentForm.email.$invalid" ng-
click="submit()">Submit</button>
Unit-5: Angular JS: Single page application
</td>
</tr>

</table>
</form>
</div>

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

mainApp.controller('studentController', function($scope) {
$scope.reset = function(){
$scope.firstName = "Sonoo";
$scope.lastName = "Jaiswal";
$scope.email = "sonoojaiswal@javatpoint.com";
}

$scope.reset();
});
</script>

</body>
</html>

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

o $dirty - states that value has been changed.


Unit-5: Angular JS: Single page application
o $invalid - states that value entered is invalid.
o $error - states the exact error.

Directive Description
ng-required Sets required attribute on an input field.
ng- Sets minlength attribute on an input field.
minlength
ng- Sets maxlength attribute on an input field. Setting the attribute to a
maxlength negative or non-numeric value, allows view values of any length.
ng-pattern Sets pattern validation error key if the ngModel value does not match
the specified RegEx expression.

<!DOCTYPE html>
<html>
<head>
<script src="~/Scripts/angular.js"></script>
</head>
<body ng-app >
<form name="studentForm" novalidate>
<label for="firstName">First Name: </label> <br />
<input type="text" name="firstName" ng-model="student.firstName"
ng-required="true" />
<span ng-show="studentForm.firstName.$touched &&
studentForm.firstName.$error.required">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="student.lastName" />
<span ng-show="studentForm.lastName.$touched &&
studentForm.lastName.$error.minlength">min 3 chars.</span>
<span ng-show="studentForm.lastName.$touched &&
studentForm.lastName.$error.maxlength">Max 10 chars.</span><br /><br />
<label for="dob">Email</label><br />
<input type="email" id="email" ng-model="student.email"
name="email" />
Unit-5: Angular JS: Single page application
<span ng-show="studentForm.email.$touched &&
studentForm.email.$error.email">Please enter valid email id.</span><br
/><br />
<input type="submit" value="Submit" />
</form>
</body>
</html>

You might also like