Professional Documents
Culture Documents
Mean Stack t Unit-II
Mean Stack t Unit-II
Statements, Arrays, Functions, Constructors, Pattern Matching using Regular Expressions. Angular Java
Script Angular JS Expressions: ARRAY, Objects, $eval, Strings, Angular JS Form Validation & Form
Submission, Single Page Application development using Angular JS.
What is JavaScript
JavaScript (js) is a light-weight object-oriented programming language which is used by several websites for scripting the webpages.
It is an interpreted, full-fledged programming language that enables dynamic interactivity on websites when applied to an HTML
document. It was introduced in the year 1995 for adding programs to the webpages in the Netscape Navigator browser. Since then,
it has been adopted by all other graphical web browsers. With JavaScript, users can build modern web applications to interact
directly without reloading the page every time. The traditional website uses js to provide several forms of interactivity and simplicity.
Although, JavaScript has no connectivity with Java programming language. The name was suggested and provided in the times
when Java was gaining popularity in the market. In addition to web browsers, databases such as CouchDB and MongoDB uses
JavaScript as their scripting and query language.
Features of JavaScript
1. All popular web browsers support JavaScript as they provide built-in execution environments.
2. JavaScript follows the syntax and structure of the C programming language. Thus, it is a structured programming
language.
3. JavaScript is a weakly typed language, where certain types are implicitly cast (depending on the operation).
4. JavaScript is an object-oriented programming language that uses prototypes rather than using classes for inheritance.
5. It is a light-weighted and interpreted language.
6. It is a case-sensitive language.
7. JavaScript is supportable in several operating systems including, Windows, macOS, etc.
8. It provides good control to the users over the web browsers.
History of JavaScript
In 1993, Mosaic, the first popular web browser, came into existence. In the year 1994, Netscape was founded by Marc Andreessen.
He realized that the web needed to become more dynamic. Thus, a 'glue language' was believed to be provided to HTML to make
web designing easy for designers and part-time programmers. Consequently, in 1995, the company recruited Brendan
Eich intending to implement and embed Scheme programming language to the browser. But, before Brendan could start, the
company merged with Sun Microsystems for adding Java into its Navigator so that it could compete with Microsoft over the web
technologies and platforms. Now, two languages were there: Java and the scripting language. Further, Netscape decided to give a
similar name to the scripting language as Java's. It led to 'Javascript'. Finally, in May 1995, Marc Andreessen coined the first code of
Javascript named 'Mocha'. Later, the marketing team replaced the name with 'LiveScript'. But, due to trademark reasons and certain
other reasons, in December 1995, the language was finally renamed to 'JavaScript'. From then, JavaScript came into existence.
Application of JavaScript
o Client-side validation,
o Dynamic drop-down menus,
o Displaying date and time,
o Displaying pop-up windows and dialog boxes (like an alert dialog box, confirm dialog box and prompt dialog box),
o Displaying clocks etc.
JavaScript Example
1. <script>
2. document.write("Hello JavaScript by JavaScript");
3. </script>
JavaScript Objects
A javaScript object is an entity having state and behavior (properties and method). For example: car, pen, bike, chair, glass, keyboard,
monitor etc.
JavaScript is template based not class based. Here, we don't create class to get the object. But, we direct create objects.
1. By object literal
2. By creating instance of Object directly (using new keyword)
3. By using an object constructor (using new keyword)
object={property1:value1,property2:value2....propertyN:valueN}
1. <script>
2. emp={id:102,name:"Shyam Kumar",salary:40000}
3. document.write(emp.id+" "+emp.name+" "+emp.salary);
4. </script>
1. <script>
2. var emp=new Object();
3. emp.id=101;
4. emp.name="Ravi Malik";
5. emp.salary=50000;
6. document.write(emp.id+" "+emp.name+" "+emp.salary);
7. </script>
Here, you need to create function with arguments. Each argument value can be assigned in the current object by using this keyword.
1. <script>
2. function emp(id,name,salary){
3. this.id=id;
4. this.name=name;
5. this.salary=salary;
6. }
7. e=new emp(103,"Vimal Jaiswal",30000);
8.
9. document.write(e.id+" "+e.name+" "+e.salary);
10. </script>
We can define method in JavaScript object. But before defining method, we need to add property in the function with same name as
method.
1. <script>
2. function emp(id,name,salary){
3. this.id=id;
4. this.name=name;
5. this.salary=salary;
6.
7. this.changeSalary=changeSalary;
8. function changeSalary(otherSalary){
9. this.salary=otherSalary;
10. }
11. }
12. e=new emp(103,"Sonoo Jaiswal",30000);
13. document.write(e.id+" "+e.name+" "+e.salary);
14. e.changeSalary(45000);
15. document.write("<br>"+e.id+" "+e.name+" "+e.salary);
16. </script>
JavaScript is a dynamic type language, means you don't need to specify type of the variable because it is dynamically used by
JavaScript engine. You need to use var here to specify the data type. It can hold any type of values such as numbers, strings etc. For
example:
JavaScript Operators
JavaScript operators are symbols that are used to perform operations on operands. For example:
1. var sum=10+20;
1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Bitwise Operators
4. Logical Operators
5. Assignment Operators
6. Special Operators
7. JavaScript Arithmetic Operators
8. Arithmetic operators are used to perform arithmetic operations on the operands. The following operators are known as
JavaScript arithmetic operators.
+ Addition 10+20 = 30
- Subtraction 20-10 = 10
The JavaScript comparison operator compares the two operands. The comparison operators are as follows:
The bitwise operators perform bitwise operations on operands. The bitwise operators are as follows:
= Assign 10+10 = 20
Operator Description
(?:) Conditional Operator returns value based on the condition. It is like if-else.
Expressions
An expression is an unit of code that JavaScript interpreter can parse and compute to produce a value.
There are simple expressions like literal values and complex which are built from simpler ones usually using operators.
Primary expressions
Primary expressions are the simplest expressions. There are three groups of primary expressions: literal values, variable references, and some
keywords.
Literal values
Literal values are constant values:
Variable references
Any identifier that appears in the code JavaScript interpreter assumes it is a variable and try to read its value.
this.name
this.displayName()
Other examples:
Function expression
Function expression defines a JavaScript function and the value of this expression is newly defined function. For example:
return x + y;
}
Object initializer creates object with literal notation and the value of this expression is newly created object. It uses curly brackets surrounding
object properties separated by commas. For example:
var obj = {
prop1: "value1",
prop2: 2
};
Array initializer creates array with literal notation and the value of this expression is newly created array. It consists of square brackets
surrounding elements separated by commas. For example:
Object creation expression creates a new instance of object. It uses the keyword new followed by a constructor invocation.
An example:
There are two ways to access a property of an object: either using the object followed by a period and an identifier or using the object (or the
array) followed by square brackets with an identifier inside. It evaluates respectively to the value of an object property or an array element.
2 obj.x // 1
3 obj['y'] // 2
5 arr[1] // 3
Invocation expression
1 func(arg);
2 obj.myMeth(x, y);
Parent object reference is a new added in ECMAScript 2015 expression using the keyword super. It evaluates to a parent object.
Spread operator
Spread operator named also rest operator allows an iterable to expand in place where multiple arguments (for function calls) or multiple elements
(for array literals) are expected.
Function call
function sum(a, b, c) {
return a + b + c;
Array literal
var motorVehicles = ['car', 'motorcycle', 'truck'];
Other expressions
There are many other expressions, such as arithmetic, comparison, logical. These are covered in the chapter on operators.
Control Statements
1. Conditional Statements
Conditional statements in a program decide the next step based on the result. They
result in either True or False. The program moves to the next step if a condition is
passed and true. However, if the condition is false, the program moves to another step.
IF
When you want to check for a specific condition with the IF condition, the inner code
Syntax:
if (condition)
//code block to be executed if condition is
}
IF-ELSE
an extended version of IF. When you want to check a specific condition and two
Syntax:
if
{
else
// code to be executed of condition is
}
As observed in an IF-ELSE statement, when the condition is satisfied, the first block of
code executes, and if the condition isn’t satisfied, the second block of code executes.
SWITCH
A switch statement is similar to IF and is useful when executing one code out of the
multiple code block execution possibilities based on the result of the expression passed.
Switch statements carry an expression, which is compared with values of the following
cases, and once a match is found, the code associated with that case executes.
Syntax:
switch (expression)
case
//code block to be
Break
case
//code block to be
Break
case
//code block to be
Break
default
//default code to be executed if none of the above case is
}
The above code contains an expression at the beginning, checked and compared with
the cases included. If the expression passed matches with case a, the code block
inside the case is executed. The same applies to cases b and n, and when the
expression
passed matches with none of the cases mentioned, it code enters the default case, and
Now that we have understood the conditional statements let’s learn about the second
2. Iterative Statement
Looping is a powerful tool for any programming language to execute instructions
repeatedly while the expression passed is satisfied. A basic example can be printing
“Hello World” 10 times. Writing the same print statement with “Hello world“ for 10
straight times will be time-consuming and impact the execution time. And this is where
looping comes in handy. There are three Iterative statements: WHILE, DO-WHILE,
WHILE
One of the control flow statements, the “while” statement, executes a code block when
the condition is satisfied. The difference between “IF” and “while” is that “IF” executes
code if the condition is satisfied, while “while” continues to repeat itself until the
condition is satisfied, unlike “IF”, which executes code only once if the condition is
Syntax:
while
{
DO-WHILE
Similar to a while loop, with a twist that keeps a condition at the end of the loop. Also
known as Exit Control Loop, DO-WHILE executes the code and checks for the condition.
Syntax:
whil
{
FOR
a for loop will execute a code block a number of times. Compared to other loops, FOR is
Syntax:
//code block to be
}
With initialization, the loop starts by using a declared variable. Then, the condition part
checks the exit condition for the loop. When this condition returns true, the code block
inside is executed. If the condition returns false or fails, the control moves to the
increment/decrement part, where the variable is updated. The values are updated until
Arrays
JavaScript Array
JavaScript array is an object that represents a collection of similar type of elements.
1. By array literal
2. By creating instance of Array directly (using new keyword)
3. By using an Array constructor (using new keyword)
As you can see, values are contained inside [ ] and separated by , (comma).
Let's see the simple example of creating and using array in JavaScript.
1. <script>
2. var emp=["Sonoo","Vimal","Ratan"];
3. for (i=0;i<emp.length;i++){
4. document.write(emp[i] + "<br/>");
5. }
6. </script>
Output of the above example
Sonoo
Vimal
Ratan
2) JavaScript Array directly (new keyword)
1. <script>
2. var i;
3. var emp = new Array();
4. emp[0] = "Arun";
5. emp[1] = "Varun";
6. emp[2] = "John";
7.
8. for (i=0;i<emp.length;i++){
9. document.write(emp[i] + "<br>");
10. }
11. </script>
Arun
Varun
John
1. <script>
2. var emp=new Array("Jai","Vijay","Smith");
3. for (i=0;i<emp.length;i++){
4. document.write(emp[i] + "<br>");
5. }
6. </script>
Let's see the list of JavaScript array methods with their description.
Methods Description
concat() It returns a new array object that contains two or more merged arrays.
copywithin() It copies the part of the given array with its own elements and returns the
modified array.
entries() It creates an iterator object and a loop that iterates over each key/value pair.
every() It determines whether all the elements of an array are satisfying the provided
function conditions.
flat() It creates a new array carrying sub-array elements concatenated recursively till
the specified depth.
flatMap() It maps all array elements via mapping function, then flattens the result into a
new array.
from() It creates a new array carrying the exact copy of another array element.
filter() It returns the new array containing the elements that pass the provided
function conditions.
find() It returns the value of the first element in the given array that satisfies the
specified condition.
findIndex() It returns the index value of the first element in the given array that satisfies
the specified condition.
forEach() It invokes the provided function once for each element of an array.
includes() It checks whether the given array contains the specified element.
indexOf() It searches the specified element in the given array and returns the index of the
first match.
keys() It creates an iterator object that contains only the keys of the array, then loops
through these keys.
lastIndexOf() It searches the specified element in the given array and returns the index of the
last match.
map() It calls the specified function for every array element and returns the new array
of() It creates a new array from a variable number of arguments, holding any type
of argument.
pop() It removes and returns the last element of an array.
reduce(function, It executes a provided function for each value from left to right and reduces
initial) the array to a single value.
reduceRight() It executes a provided function for each value from right to left and reduces
the array to a single value.
some() It determines if any element of the array passes the test of the implemented
function.
slice() It returns a new array containing the copy of the part of the given array.
toString() It converts the elements of a specified array into string form, without affecting
the original array.
unshift() It adds one or more elements in the beginning of the given array.
values() It creates a new iterator object carrying values for each index in the array
Functions
JavaScript Functions
JavaScript functions are used to perform operations. We can call JavaScript function many times to reuse the code.
Let’s see the simple example of function in JavaScript that does not has arguments.
1. <script>
2. function msg(){
3. alert("hello! this is message");
4. }
5. </script>
6. <input type="button" onclick="msg()" value="call function"/>
Test it Now
We can call function by passing arguments. Let’s see the example of function that has one argument.
1. <script>
2. function getcube(number){
3. alert(number*number*number);
4. }
5. </script>
6. <form>
7. <input type="button" value="click" onclick="getcube(4)"/>
8. </form>
Test it Now
Click
We can call function that returns a value and use it in our program. Let’s see the example of function that returns value.
1. <script>
2. function getInfo(){
3. return "hello javatpoint! How r u?";
4. }
5. </script>
6. <script>
7. document.write(getInfo());
8. </script>
Test it Now
In JavaScript, the purpose of Function constructor is to create a new Function object. It executes the code globally. However, if we
call the constructor directly, a function is created dynamically but in an unsecured way.
Syntax
Parameter
Method Description
apply() It is used to call a function contains this value and a single array of arguments.
call() It is used to call a function contains this value and an argument list.
Example 1
1. <script>
2. var add=new Function("num1","num2","return num1+num2");
3. document.writeln(add(2,5));
4. </script>
Output
7
Example 2
1. <script>
2. var pow=new Function("num1","num2","return Math.pow(num1,num2)");
3. document.writeln(pow(2,3));
4. </script>
Output:
Constructors
Points to remember
1. <script>
2. class Employee {
3. constructor() {
4. this.id=101;
5. this.name = "Martin Roy";
6. }
7. }
8. var emp = new Employee();
9. document.writeln(emp.id+" "+emp.name);
10. </script>
Output:
1. <script>
2. class CompanyName
3. {
4. constructor()
5. {
6. this.company="Javatpoint";
7. }
8. }
9. class Employee extends CompanyName {
10. constructor(id,name) {
11. super();
12. this.id=id;
13. this.name=name;
14. }
15. }
16. var emp = new Employee(1,"John");
17. document.writeln(emp.id+" "+emp.name+" "+emp.company);
18. </script>
Output:
1 John Javatpoint
The search pattern can be used for text search and text replace operations.
When you search for data in a text, you can use this search pattern to describe what you are searching for.
Regular expressions can be used to perform all types of text search and text replace operations.
Syntax
/pattern/modifiers;
Example
/w3schools/i;
Example explained:
/w3schools/i is a regular expression.
The search() method uses an expression to search for a match, and returns the position of the match.
The replace() method returns a modified string where the pattern is replaced.
Example
Use a string to do a search for "W3schools" in a string:
Try it Yourself »
6
Using String replace() With a String
The replace() method replaces a specified value with another value in a string:
Visit W3Schools!
Modifier Description
g Perform a global match (find all matches rather than stopping after the first match)
Metacharacter Description
\d Find a digit
\b Find a match at the beginning of a word like this: \bWORD, or at the end of a
word like this: WORD\b
\uxxxx Find the Unicode character specified by the hexadecimal number xxxx
Quantifier Description
Using test()
The test() method is a RegExp expression method.
It searches a string for a pattern, and returns true or false, depending on the result.
Example
const pattern = /e/;
pattern.test("The best things in life are free!");
Since there is an "e" in the string, the output of the code above will be:
true
You don't have to put the regular expression in a variable first. The two lines above can be shortened to one:
Using exec()
The exec() method is a RegExp expression method.
It searches a string for a specified pattern, and returns the found text as an object.
Example
/e/.exec("The best things in life are free!");
Angular.JS expressions are used to bind data to HTML the same way as the ng-bind directive. AngularJS displays the
data exactly at the place where the expression is placed.
<!DOCTYPE html>
<html>
<head>
<meta chrset="UTF 8">
<title>Event Registration</title>
</head>
<body>
<script src="https://code.angularjs.org/1.6.9/angular-route.js"></script>
<script src="https://code.angularjs.org/1.6.9/angular.min.js"></script>
<div ng-app="">
Addition : {{6+9}}
</div>
</body>
</html>
Code Explanation:
1. The ng-app directive in our example is blank as shown in above screenshot. This only means that there is
no module to assign controllers, directives, services attached to the code.
2. We are adding a simple expression which looks at the addition of 2 numbers.
If the code is executed successfully, the following Output will be shown when you run your code in the browser.
Output:
It can be seen that the addition of the two numbers 9 and 6 take place and the added value of 15 is
displayed.
Angular.JS Numbers
Expressions can be used to work with numbers as well. Let’s look at an example of Angular.JS expressions with
numbers.
In this example, we just want to show a simple multiplication of 2 number variables called margin and profit and
displayed their multiplied value.
Code Explanation:
1. The ng-init directive is used in angular.js to define variables and their corresponding values in the view
itself. It’s somewhat like defining local variables to code in any programming language. In this case, we
are defining 2 variables called margin and profit and assigning values to them.
2. We are then using the 2 local variables and multiplying their values.
If the code is executed successfully, the following Output will be shown when you run your code in the browser.
Output:
AngularJS Strings
Expressions can be used to work with strings as well. Let’s look at an example of Angular JS expressions with strings.
In this example, we are going to define 2 strings of “firstName” and “lastName” and display them using expressions
accordingly.
<!DOCTYPE html>
<html>
<head>
<meta chrset="UTF 8">
<title>Event Registration</title>
</head>
<body>
<script src="https://code.angularjs.org/1.6.9/angular-route.js"></script>
<script src="https://code.angularjs.org/1.6.9/angular.min.js"></script>
First Name : {{firstName}}<br>
last Name : {{lastName}}
</div>
</body>
</html>
Code Explanation:
1. The ng-init directive is used define the variables firstName with the value “Guru” and the variable
lastName with the value of “99”.
2. We are then using expressions of {{firstName}} and {{lastName}} to access the value of these
variables and display them in the view accordingly.
If the code is executed successfully, the following Output will be shown when you run your code in the browser.
Output:
Angular.JS Objects
Expressions can be used to work with JavaScript objects as well.
Let’s look at an example of Angular.JS expressions with javascript objects. A javascript object consists of a name-
value pair.
Syntax:
In this example, we are going to define one object as a person object which will have 2 key value pairs of “firstName”
and “lastName”
<!DOCTYPE html>
<html>
<head>
<meta chrset="UTF 8">
<title>Event Registration</title>
</head>
<body>
<script src="https://code.angularjs.org/1.6.9/angular-route.js"></script>
<script src="https://code.angularjs.org/1.6.9/angular.min.js"></script>
First Name : {{person.firstName}}<br>
Last Name : {{person.lastName}}
</div>
</body>
</html>
Code Explanation:
1. The ng-init directive is used to define the object person which in turn has key value pairs of
firstName with the value “Guru” and the variable lastName with the value of “99”.
2. We are then using expressions of {{person.firstName}} and {{person.secondName}} to access the value
of these variables and display them in the view accordingly. Since the actual member variables are part of
the object person, they have to access it with the dot (.) notation to access their actual value.
If the code is executed successfully, the following Output will be shown when you run your code in the browser.
Output:
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.
<!DOCTYPE html>
<html>
<head>
<meta chrset="UTF 8">
<title>Event Registration</title>
</head>
<body>
<script src="https://code.angularjs.org/1.6.9/angular-route.js"></script>
<script src="https://code.angularjs.org/1.6.9/angular.min.js"></script>
Student Marks<br>
Subject1 : {{marks[0] }}<br>
Subject2 : {{marks[1] }}<br>
Subject3 : {{marks[2] }}<br>
</div>
</body>
</html>
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:
Difference between expression and $eval
The $eval function allows one to evaluate expressions from within the controller itself. So while expressions are
used for evaluation in the view, the $eval is used in the controller function.
this example,
We are just going to use the $eval function to add 2 numbers and make it available in the scope object so that it can be
shown in the view.
<!DOCTYPE html>
<html>
<head>
<meta chrset="UTF 8">
<title>Event Registration</title>
</head>
<body>
<script src="https://code.angularjs.org/1.6.9/angular-route.js"></script>
<script src="https://code.angularjs.org/1.6.9/angular.min.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
$scope.value=$scope.$eval('a+b');
});
</script>
</body>
</html>
Code Explanation:
1. We are first defining 2 variables ‘a’ and ‘b’, each holding a value of 1.
2. We are using the $scope.$eval function to evaluate the addition of the 2 variables and assigning it to the
scope variable ‘value’.
3. We are then just displaying the value of the variable ‘value’ in the view.
If the code is executed successfully, the following Output will be shown when you run your code in the browser.
Output:
It also holds the information about whether the input fields have been touched, or modified, or not.
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>
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. <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", []);
73. mainApp.controller('studentController', function($scope) {
74. $scope.reset = function(){
75. $scope.firstName = "Sonoo";
76. $scope.lastName = "Jaiswal";
77. $scope.email = "sonoojaiswal@javatpoint.com";
78. }
79. $scope.reset();
80. });
81. </script>
82. </body>
83. </html>
Angular follows MVC architecture, so every angular app consists of different modules.
app.controller('FirstController', function($scope) {
});
The module created in the first step and the controller performed in the second step specify both in the ng-controller attribute.
<!doctype html>
<html ng-app="myApp">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.min.js"></
script>
</head>
<body ng-controller="FirstController">
<h1>{{message}}</h1>
<script src="app.js"></script>
</body>
</html>
<!doctype html>
<html ng-app="myApp">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.min.js"></
script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular-
route.min.js"></script>
</head>
<body>
<div ng-view></div>
<script src="app.js"></script>
</body>
</html>
A templateUrl and a controller must be specified for each route. In cases where a user attempts to navigate to an unexistent route, an
exception must be handled. Then, the user can be redirected to the “/” route using an “otherwise” function.
app.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl : 'pages/first.html',
controller : 'FirstController'
})
.when('/blog', {
templateUrl : 'pages/second.html',
controller : 'SecondController'
})
.when('/about', {
templateUrl : 'pages/third.html',
controller : 'ThirdController'
})
.otherwise({redirectTo: '/'});
});
app.controller('FirstController', function($scope) {
});
app.controller('SecondController', function($scope) {
});
app.controller('ThirdController', function($scope) {
});
first.html
<h1>First</h1>
<h3>{{message}}</h3>
second.html
<h1>Second</h1>
<h3>{{message}}</h3>
third.html
<h1>Third</h1>
<h3>{{message}}</h3>
<!doctype html>
<html ng-app="myApp">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.min.js"></
script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular-
route.min.js"></script>
</head>
<body>
<a href="#/">First</a>
<a href="#/second">Second</a>
<a href="#/third">Third</a>
<div ng-view></div>
<script src="app.js"></script>
</body>
</html>
Step 9: Include the HTML of the Above Pages to Index.html file with Script Tag
<!doctype html>
<html ng-app="myApp">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.min.js"></
script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular-
route.min.js"></script>
</head>
<body>
<h1>First</h1>
<h3>{{message}}</h3>
</script>
<h1>Second</h1>
<h3>{{message}}</h3>
</script>
<h1>Third</h1>
<h3>{{message}}</h3>
</script>
<a href="#/">First</a>
<a href="#/second">Second</a>
<a href="#/third">Third</a>
<div ng-view></div>
<script src="app.js"></script>
</body>
</html>
That’s it! After successfully performing the above steps, you can easily create single-page applications using Angular and
also simplify many other complex tasks of your projects.