0% found this document useful (0 votes)
41 views53 pages

Angular Lab

The document is a laboratory manual for the Angular JS and Node JS course (21CSL581) at ATME College of Engineering for the academic year 2023-24. It outlines the institute's mission and vision, course objectives, program outcomes, and assessment details, as well as the course syllabus and teaching-learning process. Additionally, it includes resources, learning activities, and the correlation of course outcomes with program outcomes.

Uploaded by

madhu
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)
41 views53 pages

Angular Lab

The document is a laboratory manual for the Angular JS and Node JS course (21CSL581) at ATME College of Engineering for the academic year 2023-24. It outlines the institute's mission and vision, course objectives, program outcomes, and assessment details, as well as the course syllabus and teaching-learning process. Additionally, it includes resources, learning activities, and the correlation of course outcomes with program outcomes.

Uploaded by

madhu
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/ 53

ATME COLLEGE OF ENGINEERING

13th KM Stone, Bannur Road, Mysore - 560 028

DEPARTMENT OF COMPUTER SCIENCE


&
ENGINEERING
(ACADEMIC YEAR 2023-24)

LABORATORY MANUAL
SUBJECT: ANGULAR JS & NODE JS

SUBJECT CODE: 21CSL581

SEMESTER: V
Institute Mission & Vision

Vision
 Development of academically excellent, culturally vibrant, socially
responsible and globally competent human resources.

Mission
 To keep pace with advancements in knowledge and make the students
competitive and capable at the global level.
 To create an environment for the students to acquire the right physical,
intellectual, emotional and moral foundations and shine as torch
bearers of tomorrow’s society.
 To strive to attain ever-higher benchmarks of educational excellence.

Department of Computer Science & Engineering

Vision of the Department

 To develop highly talented individuals in Computer Science and


Engineering to deal with real world challenges in industry, education,
research and society.

Mission of the Department

 To inculcate professional behavior, strong ethical values, innovative


research capabilities and leadership abilities in the young minds & to
provide a teaching environment that emphasizes depth, originality and
critical thinking.

 Motivate students to put their thoughts and ideas adoptable by industry


or to pursue higher studies leading to research.
Angular JS & Node JS – 21CSL581

Program Outcomes (POs)

1. Engineering Knowledge: Apply the knowledge of mathematics, science, engineering fundamentals,


andan engineering specialization to the solution of complex engineering problems.

2. Problem Analysis: Identify, formulate, research literature, and analyze complex engineering problems
reaching substantiated conclusions using first principles of mathematics, natural sciences, and engineering
sciences

Design/development of Solutions: Design solutions for complex engineering problems and design system
components or processes that meet the specified needs with appropriate consideration for the public health
and safety, and the cultural, societal, and environmental considerations.

4. Conduct Investigations of Complex Problems: Use research-based knowledge and research methods
including design of experiments, analysis and interpretation of data, and synthesis of the information to
provide valid conclusions.

5. Modern Tool usage: Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modeling to complex engineering activities with an
understanding of the limitations.

6. The Engineer and Society: Apply reasoning informed by the contextual knowledge to assess societal,
health, safety, legal and cultural issues and the consequent responsibilities relevant to the professional
engineering practice.

7. Environment and Sustainability: Understand the impact of the professional engineering solutions in
societal and environmental contexts, and demonstrate the knowledge of, and need for sustainable
development.

8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms of
theengineering practice.

9. Individual and Team Work: Function effectively as an individual, and as a member or leader in
diverseteams, and in multidisciplinary settings.

10. Communication: Communicate effectively on complex engineering activities with the engineering
community and with society at large, such as, being able to comprehend and write effective reports and
designdocumentation, make effective presentations, and give and receive clear instructions.

11. Project Management and Finance: Demonstrate knowledge and understanding of the engineering
and management principles and apply these to one’s own work, as a member and leader in a team, to
manage projects and in multidisciplinary environments.

12. Life-long Learning: Recognize the need for, and have the preparation and ability to engage in
independent and life-long learning in the broadest context of technological change.
Department of CS&E, ATMECE, Mysuru.
Angular JS & Node JS – 21CSL581

Program Specific Outcomes (PSOs)

PSO1: Ability to apply skills in the field of algorithms, database design, web design, cloud computing
and data analytics.

PSO2: Apply knowledge in the field of computer networks for building network and internet-based
applications.

Program Educational Objectives (PEOs):

1. Empower students with a strong basis in the mathematical, scientific and engineering
fundamentals to solve computational problems and to prepare them for employment, higher
learning and R&D.

2. Gain technical knowledge, skills and awareness of current technologies of computer science
engineering and to develop an ability to design and provide novel engineering solutions for
software/hardware problems through entrepreneurial skills.

3. Exposure to emerging technologies and work in teams on interdisciplinary projects with


effective communication skills and leadership qualities.

4. Ability to function ethically and responsibly in a rapidly changing environment by applying


innovative ideas in the latest technology, to become effective professionals in Computer Science
to bear a life-long career in related areas.

Department of CS&E, ATMECE, Mysuru.


Angular JS & Node JS – 21CSL581

Course Syllabi with CO's


Faculty Mr. Anil Kumar C J Academic Year: 2023 - 2024
Name: Mrs. Hamsa A S

Department: Computer Science & Engineering


Contact Total
Course
Course Title Core/AEC/Elec Prerequisite Hours Hrs/
Code tive
L T P Sessions
Basics of
Angular JS AEC Web 1 - - 12T +
21CSL581 and Node JS Programming 12P
and JAVA
Script
1. To learn the basics of Angular JS.
Course 2. To understand the Angular JS Modules.
Objective 3. To implement Forms, inputs and Services
4. To implement Directives and Databases
5. To understand basics of Node JS.

Topics Covered as per Syllabus


Module-1
Introduction To Angular JS:
Introduction – Features – Angular JS Model-View-Controller – Expression -Directives and
Controllers.
Module-2
Angular JS Modules:
Arrays –Working with ng-model – Working with Forms – Form Validation – Error Handling
with Forms – Nested Forms with ng-form – Other Form Controls.
Module-3
Directives& Building Databases:
Part I- Filters – Using Filters in Controllers and Services – Angular JS Services – Internal
Angular JS Services – Custom Angular JS Services.
Module-4
Directives& Building Databases:
Part-II- Directives – Alternatives to Custom Directives – Understanding the Basic options –
Interacting with Server –HTTP Services – Building Database, Front End and Backend
Module-5
Introduction to NODE.JS:
Introduction –Using the Terminals – Editors –Building a Webserver with Node – The HTTP
Module – Views and Layouts.

Department of CS&E, ATMECE, Mysuru.


Angular JS & Node JS – 21CSL581

Teaching-Learning Process Chalk and board, Active Learning, practical based learning
Course Outcomes (Course Skill Set)
At the end of the course the student will be able to:
CO 1. Describe the features of Angular JS.
CO 2. Recognize the form validations and controls.
CO 3. Implement Directives and Controllers.
CO 4. Evaluate and create database for simple application.
CO 5. Plan and build webservers with node using Node .JS.
Assessment Details (both CIE and SEE)

The weightage of Continuous Internal Evaluation (CIE) is 50% and for Semester End Exam
(SEE) is 50%. The minimum passing mark for the CIE is 40% of the maximum marks (20
marks). A student shall be deemed to have satisfied the academic requirements and earned the
credits allotted to each course. The student has to secure not less than 35% (18 Marks out of 50)
in the semester-end examination (SEE). The student has to secure a minimum of 40% (40 marks
out of 100) in the sum total of the CIE (Continuous Internal Evaluation) and SEE (Semester End
Examination) taken together.

Continuous Internal Evaluation (CIE):


NOTE: List of experiments to be prepared by the faculty based on the syllabus mentioned above
CIE marks for the practical course is 50 Marks.
The split-up of CIE marks for record/ journal and test are in the ratio 60:40.
 Each experiment to be evaluated for conduction with observation sheet and record write-up.
Rubrics for the evaluation of the journal/write-up for hardware/software experiments
designed by the faculty who is handling the laboratory session and is made known to
students at the beginning of the practical session.
 Record should contain all the specified experiments in the syllabus and each experiment
write-up will be evaluated for 10 marks.
 Total marks scored by the students are scaled downed to 30 marks (60% of maximum marks).
 Weightage to be given for neatness and submission of record/write-up on time.
 Department shall conduct 02 tests for 100 marks, the first test shall be conducted after the
8th
week of the semester and the second test shall be conducted after the 14th week of the
semester.
 In each test, test write-up, conduction of experiment, acceptable result, and procedural
knowledge will carry a weightage of 60% and the rest 40% for viva-voce.
 The suitable rubrics can be designed to evaluate each student’s performance and learning
ability. Rubrics suggested in Annexure-II of Regulation book
 The average of 02 tests is scaled down to 20 marks (40% of the maximum marks).
The Sum of scaled-down marks scored in the report write-up/journal and average marks of two
tests is the total CIE marks scored by the student.

Department of CS&E, ATMECE, Mysuru.


Angular JS & Node JS – 21CSL581

Semester End Evaluation (SEE):


 SEE marks for the practical course is 50 Marks.
 SEE shall be conducted jointly by the two examiners of the same institute, examiners
are appointed by the University
 All laboratory experiments are to be included for practical examination.
 (Rubrics) Breakup of marks and the instructions printed on the cover page of the answer
script to be strictly adhered to by the examiners. OR based on the course requirement
evaluation rubrics shall be decided jointly by examiners.
 Students can pick one question (experiment) from the questions lot prepared by the internal
/external examiners jointly.
 valuation of test write-up/ conduction procedure and result/viva will be conducted jointly by examiners.
 General rubrics suggested for SEE are mentioned here, writeup-20%, Conduction procedure and result in -
60%, Viva-voce 20% of maximum marks. SEE for practical shall be evaluated for 100 marks and scored
marks shall be scaled down to 50 marks (however, based on course type, rubrics shall be decided by the
examiners)
 The duration of SEE is 02 hours
Rubrics suggested in Annexure-II of Regulation book

Suggested Learning Resources:


Textbooks
1. Adam Freeman - ProAngular JS, Apress, First Edition, 2014.
2. ShyamSeshadri, Brad Green –“AngularJS: Up and Running: Enhanced Productivity with Structured
Web Apps”, Apress, O'Reilly Media, Inc.
3. AgusKurniawan–“AngularJS Programming by Example”, First Edition, PE Press, 2014.
Reference Books
1. Brad Dayley, “Learning Angular JS”, Addison-Wesley Professional, First Edition, 2014.
2. Steve Hoberman, “Data Modeling for MongoDB”, Technics Publication, First Edition, 2014..
Weblinks and Video Lectures (e-Resources):
1. Introduction to Angular JS : https://www.youtube.com/watch?v=HEbphzK-0xE
2. Angular JS Modules : https://www.youtube.com/watch?v=gWmOKmgnQkU
3. Directives& Building Databases: https://www.youtube.com/watch?v=R_okHflzgm0
4. Introduction to NODE .JS: https://www.youtube.com/watch?v=8u1o-OmOeGQ
5. https://www.youtube.com/watch?v=7F1nLajs4Eo
6. https://www.youtube.com/watch?v=t7x7c-x90FU
Activity Based Learning (Suggested Activities in Class)/ Practical Based learning

 Demonstration of simple projects

The Correlation of Course Outcomes (CO’s) and Program Outcomes (PO’s)


Subject 21CSL581 TITLE: Angular JS and Node JS Faculty
Code: Name:
List of Program
Outcomes
Course Total
Outcome PO 1 PO 2 PO 3 PO 4 PO 5 PO PO PO 8 PO PO PO PO 12
s 6 7 9 10 11
CO-1 2 1 1 1 - - - - - - - - 5
CO-2 2 2 1 - - - - - - - - 2 7
CO-3 2 2 1 - - - - - - - - 1 6
CO-4 2 2 2 1 - - - - - - - 2 9
CO-5 2 2 1 1 - - - - - - - 6
Total - - - - - - -
10 9 6 3 5 33
Department of CS&E, ATMECE, Mysuru.
Angular JS & Node JS – 21CSL581

The Correlation of Course Outcomes (CO’s) and Program Specific Outcomes (PSO’s)

Subject TITLE: Angular JS and Node JS Faculty Mr. Anil Kumar C J


Code: 21CSL581 Name: Mrs. Hamsa A S
List of Program Specific
Outcomes
Course Tot
PSO-1 PSO-2 al
Outcomes
CO-1 1 - 1
CO-2 2 - 2
CO-3 3 - 3
CO-4 3 - 3
CO-5 3 - 3
Total 12 - 12

Note: 3 = Strong Contribution, 2 = Average Contribution, 1 = Weak Contribution, - = No Contribution

Department of CS&E, ATMECE, Mysuru.


Angular JS & Node JS – 21CSL581

Angular JS Features

Directive Description
ng-app It defines the root element of an application.

ng-bind It binds the content of an html element to application data.

ng-bind-html It binds the inner HTML of an HTML element to application


data, and also removes dangerous code from the html string.

ng-bind- It specifies that the text content should be replaced with a template.
template

ng-blur It specifies a behavior on blur events.

ng-change It specifies an expression to evaluate when content is being changed


by theuser.

ng-checked It specifies if an element is checked or not.

ng-class It specifies css classes on html elements.

ng-class-even It is same as ng-class, but will only take effect on even rows.

ng-class-odd It is same as ng-class, but will only take effect on odd rows.

ng-click It specifies an expression to evaluate when an element is being clicked.

ng-cloak It prevents flickering when your application is being loaded.

ng-controller It defines the controller object for an application.

ng-copy It specifies a behavior on copy events.

ng-csp It changes the content security policy.

ng-cut It specifies a behavior on cut events.

ng-dblclick It specifies a behavior on double-click events.

ng-focus It specifies a behavior on focus events.

ng-hide It hides or shows html elements.

ng-href It specifies a URL for the <a> element.

ng-if It removes the html element if a condition is false.

Department of CS&E, ATMECE, Mysuru.


Angular JS & Node JS – 21CSL581

CUSTOM DIRECTIVES
In AngularJS, custom directives are a way to extend the functionality of HTML by creating
your own reusable HTML elements or attributes. Custom directives enable you to encapsulate
complex behaviors and encapsulate them into a single, reusable component. They are a
fundamental building block for creating dynamic and interactive web applications.

Creating a custom directive in AngularJS involves using the directive function of an AngularJS
module. Here's a general outline of how to create a custom directive (Method 1 – inline
template):
1. Define an AngularJS Module: First, create an AngularJS module using the
angular.module function. This module serves as the container for your custom
directive.

2. Create the Directive: Use the directive method on your module to create the directive.
This method takes the name of the directive and a factory function as arguments.

3. Directive Factory Function: The factory function defines the behavior and appearance
of the custom directive. It returns an object with specific properties and methods, such
as restrict (to define how the directive can be used), template (to specify the HTML
template), and link functions (to define behavior).
4. Use the Directive: In your HTML, you can now use your custom directive by its name
as an HTML element or attribute.
Interacting with Server

A Content Delivery Network (CDN) is a network of distributed servers located in various data
centers around the world. CDNs are designed to deliver web content, such as images, videos,
scripts, and other static assets, to users with high availability and performance. They work by
caching content on multiple servers and serving it from the server that is geographically closest
to the user, reducing latency and improving page load times.

In the below program, a CDN is used to load the AngularJS library into your web page. Here's
where it is used:
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>

In this line, you include the AngularJS library by specifying its source URL. This URL points
to a file on Google's CDN that hosts the AngularJS library. When a user opens your web page,
their browser fetches AngularJS from the CDN server closest to their location, which can
significantly speed up the loading of the library.

Department of CS&E, ATMECE, Mysuru.


Angular JS & Node JS – 21CSL581

MODULE 1
Introduction to Angular JS: Introduction – Features – Angular JS Model-View-Controller –
Expression -Directives and Controllers.

Program 1:

A) Create a basic AngularJS application to understand the foundational concepts of


AngularJS. You will set up a simple webpage and initialize AngularJS, showcasing
how it enables dynamic content binding.

<!DOCTYPE html>
<html ng-app="myApp">
<head>
<title>Getting Started with AngularJS</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body>
<div ng-controller="MyCtrl">
<h1>Welcome to AngularJS!</h1>
<p>Dynamic Content Binding Example:</p>
<p>Enter your name: <input type="text" ng-model="name"></p>
<p>Hello, {{ name }}!</p>
</div>

<script>
angular.module('myApp', [])
.controller('MyCtrl', function($scope) {
// Initialize scope variables
$scope.name = "User";
});
</script>
</body>
</html>

Department of CS&E, ATMECE, Mysuru.


Angular JS & Node JS – 21CSL581

Explanation:

In this code,

1) We have a simple HTML page that uses AngularJS to demonstrate dynamic content
binding.  The ng-app attribute defines the AngularJS application module, and the ng-
controller attribute defines a controller called MyCtrl.

2) The controller initializes a variable name in the scope, and the value is bound to an
input field and displayed dynamically on the page.

3) When you type your name in the input field, it updates the greeting message below.

4) This is a fundamental example to showcase AngularJS's ability to bind data and create
dynamic interactions in web applications.

5) Students can use this as a starting point to explore AngularJS further.

Output:

Department of CS&E, ATMECE, Mysuru.


Angular JS & Node JS – 21CSL581

B) Create a basic AngularJS application that demonstrates dynamic content binding


through asimple to-do list.

Code:
<!DOCTYPE html>

<html ng-app="myApp">
<head>

<title>Simple To-Do List with AngularJS</title>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body>

<div ng-controller="MyCtrl">
<h1>Simple To-Do List with AngularJS</h1>

<!-- Display the to-do list -->


<ul>
<li ng-repeat="task in tasks">{{ task }}</li>

</ul>

<!-- Input field to add tasks -->


<input type="text" ng-model="newTask" placeholder="Add a new task">

<button ng-click="addTask()">Add Task</button>


</div>

<script>
angular.module('myApp', [])

.controller('MyCtrl', function($scope) {
// Initialize an empty array for tasks

$scope.tasks = [];

// Function to add a new task


$scope.addTask = function() {
if ($scope.newTask) {

Department of CS&E, ATMECE, Mysuru.


Angular JS & Node JS – 21CSL581

$scope.tasks.push($scope.newTask);
$scope.newTask = ''; // Clear the input field
}

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

</html>

Explanation:
In this example, we create a simple to-do list application:

1. The to-do list is displayed using the ng-repeat directive, which iterates over the tasks
and displays them in an unordered list.

2. An input field and a button allow users to add new tasks to the list. The ng-model
directive binds the input field to the newTask variable.

3. The addTask function is called when the "Add Task" button is clicked. It adds a new
task to the list and clears the input field.
This program serves as a hands-on example for beginners to understand how AngularJS enables
dynamic content binding, making it easy to create interactive web applications.

Students can interact with the to-do list, add tasks, and see how the content updates
dynamically.

Output:

Department of CS&E, ATMECE, Mysuru.


Angular JS & Node JS – 21CSL581

Program 2:
A) Create a basic AngularJS application to build a simple number calculator (build a
calculator that can perform addition and subtraction)

Code:
<!DOCTYPE html>

<html ng-app="myApp">
<head>

<title>Number Calculator with AngularJS</title>


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

</head>
<body>
<div ng-controller="CalculatorCtrl">
<h1>Number Calculator with AngularJS</h1>

<p>Enter a number:</p>

<input type="number" ng-model="number1">


<p>Enter another number:</p>

<input type="number" ng-model="number2">


<p>Result: {{ number1 }} + {{ number2 }} = {{ number1 + number2 }}</p>
<p>Result: {{ number1 }} - {{ number2 }} = {{ number1 - number2 }}</p>

</div>
<script>
angular.module('myApp', [])

.controller('CalculatorCtrl', function($scope) {

$scope.number1 = 0;
$scope.number2 = 0;

});
</script>
</body>

</html>
Department of CS&E, ATMECE, Mysuru.
Angular JS & Node JS – 21CSL581

Explanation:
In this program, we:

1. Create a simple calculator that allows you to enter two numbers using input fields with
ng-model.

2. Display the results of addition and subtraction using AngularJS expressions: {{


number1 + number2 }} and {{ number1 - number2 }}.
3. The program initializes both input fields to 0 when the page loads.

You can enter numbers in the input fields, and the program will instantly display the results of
addition and subtraction. This example illustrates how AngularJS can be used for simple
calculations and dynamic content updates on a web page.

Output:

Department of CS&E, ATMECE, Mysuru.


Angular JS & Node JS – 21CSL581

B) Create a simple web page that utilizes various AngularJS directives to enhance its
functionality and create controllers to manage the application's behavior.

Code:
<!DOCTYPE html>
<html ng-app="myApp">
<head>

<title>Exploring AngularJS Features</title>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>

<body>
<div ng-controller="MyCtrl">

<h1>Exploring AngularJS Features</h1>

<!-- Using ng-if directive to conditionally display content -->


<div ng-if="showContent">
<p>Conditional Content:</p>

<p>{{ conditionalMessage }}</p>


</div>

<!-- Using ng-repeat directive to iterate over a list -->


<p>Iterating Over a List:</p>
<ul>

<li ng-repeat="item in itemList">{{ item }}</li>


</ul>

<!-- Using a custom controller function -->


<p>Controller Function:</p>

Department of CS&E, ATMECE, Mysuru.


Angular JS & Node JS – 21CSL581

<button ng-click="updateMessage()">Update Message</button>


<p>{{ customMessage }}</p>

</div>

<script>
angular.module('myApp', [])

.controller('MyCtrl', function($scope) {
$scope.showContent = true;

// Using ng-repeat with a list


$scope.itemList = ["Item 1", "Item 2", "Item 3"];

// Custom controller function


$scope.customMessage = "Initial Message";
$scope.updateMessage = function() {
$scope.customMessage = "Updated Message";

};

});
</script>
</body>

</html>

Explanation:
In this code, we explore various AngularJS features:

1. Using ng-if Directive: We conditionally display content based on the value of the
showContent variable.
2. Using ng-repeat Directive: We use the ng-repeat directive to iterate over a list and
display each item in an unordered list.

3. Custom Controller Function: We create a custom function, updateMessage(), within


the controller to update the message when a button is clicked.

This code provides a basic example of how to utilize AngularJS directives and controllers to
enhance the functionality of a web page. Students can use this as a starting point to explore
these features in more detail.

Department of CS&E, ATMECE, Mysuru.


Angular JS & Node JS – 21CSL581

Output:

Department of CS&E, ATMECE, Mysuru.


Angular JS & Node JS – 21CSL581

MODULE 2
Angular JS Modules: Arrays –Working with ng-model – Working with Forms – Form
Validation – Error Handling with Forms – Nested Forms with ng-form – Other Form Controls.

Program 3
A simple AngularJS program that demonstrates basic filtering and searching in a "List
of Countries" application.
Code:
<!DOCTYPE html>

<html ng-app="myApp">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<body>
<div ng-controller="myCtrl">

<h2>List of Countries</h2>

<!-- Input for filtering countries -->


<input type="text" ng-model="searchText" placeholder="Search for a country">

<!-- List of countries with filtering -->

<ul>
<li ng-repeat="country in countries | filter: searchText">

{{ country }}
</li>
</ul>

</div>
<script>

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


app.controller("myCtrl", function($scope) {

$scope.countries = [
"INDIA",
"Canada",

"Australia",
Department of CS&E, ATMECE, Mysuru.
Angular JS & Node JS – 21CSL581

"United Kingdom",

"Germany",

"France",
"Japan",

"China",
"USA",
"Brazil",

];
$scope.searchText = "";

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

Output:

Explanation:
In this "List of Countries" application:

• The ng-model is used to bind the input field to the searchText variable. Users can
enter text in the input field to filter and search for countries.

• The ng-repeat directive is used to iterate through the countries array and display the
countries. The filter filter is applied to the list to dynamically filter and display
countries based on the value in the searchText variable.
This program is a simple example for learners to understand basic filtering and searching in
AngularJS. Users can search for countries in the list by entering text in the search input field.

Department of CS&E, ATMECE, Mysuru.


Angular JS & Node JS – 21CSL581

Program 4
Write a program that conditionally display different HTML content based on the value
of a variable.
Code:
<!DOCTYPE html>

<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>

<body ng-app="">
Choose your favorite topic:

<select ng-model="myVar">
<option value="animals">Zoology
<option value="tuts">Tutorials
<option value="cars">Cars

<option value="bikes">Bikes

</select>
<hr>

<div ng-switch="myVar">
<div ng-switch-when="animals">
<h1>Zoology</h1>

<p>Welcome to a world of zoology.</p>


</div>

<div ng-switch-when="tuts">
<h1>Tutorials</h1>

<p>Learn from examples.</p>


</div>

<div ng-switch-when="cars">
<h1>Cars</h1>

<p>Read about cars.</p>


</div>

Department of CS&E, ATMECE, Mysuru.


Angular JS & Node JS – 21CSL581

<div ng-switch-when="bikes">
<h1>bikes</h1>

<p>Read about bikes.</p>

</div>
<div ng-switch-default>
<h1>Switch</h1>
<p>Select topic from the dropdown, to switch the content of this DIV.</p>

</div>

</div>
<hr>

<p>The ng-switch directive hides and shows HTML sections depending on a certain
value.</p>
</body>

</html>

Explanation:
This program introduces the concept of using the AngularJS ng-switch directive, which allows
you to conditionally display different HTML content based on the value of a variable (myVar).
Let's focus on the new concepts introduced compared to the previous two programs:

1. <select> and ng-model Directive:

• A <select> element is used to create a dropdown menu with multiple options.

• The ng-model directive is used to bind the selected option to a variable (myVar),
which will control the content displayed based on the selected option.
2. ng-switch Directive:

• The <div> element with the ng-switch directive is used to define a container for
content that will be conditionally displayed based on the value of myVar.
3. ng-switch-when Directive:

• Inside the ng-switch container, there are multiple <div> elements, each with the
ng-switch-when directive. These elements specify different values of myVar for
which specific content should be displayed.

4. ng-switch-default Directive:

Department of CS&E, ATMECE, Mysuru.


Angular JS & Node JS – 21CSL581

• There is also an <div> element with the ng-switch-default directive, which


specifies the default content to be displayed when myVar doesn't match any of
the specified values.

5. Conditional Content:
The content within each <div> element is conditionally displayed based on the value of
myVar. For example, when myVar is "tuts," the content under <div ng-switch-
when="tuts"> is displayed.
6. Interactivity:
The user can choose their favorite topic from the dropdown menu. Depending on the
selected topic, the content displayed on the page changes dynamically.
7. <hr> Elements:
The program also includes horizontal rule (<hr>) elements to separate different sections
of content.
In summary, this program demonstrates how to use the ng-switch directive in AngularJS to
create conditional content based on the value of a variable (myVar). It allows you to
dynamically switch and display different sections of content on the web page based on user
selections from the dropdown menu.

Output:

Department of CS&E, ATMECE, Mysuru.


Angular JS & Node JS – 21CSL581

MODULE 3
Directives & Building Databases: Part I- Filters – Using Filters in Controllers and Services –
Angular JS Services – Internal Angular JS Services – Custom Angular JS Services

Program 5
Build a simple text transformation application that allows users to convert text touppercase and lowercase
Code:
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<body ng-app="textApp">

<div ng-controller="TextController">
<h2>Text Transformer</h2>
<input type="text" ng-model="inputText" placeholder="Enter Text">
<button ng-click="transformToUppercase()">To Uppercase</button>
<button ng-click="transformToLowercase()">To Lowercase</button>

<p>Transformed Text: {{ transformedText }}</p>


</div>

<script>
var app = angular.module('textApp', []);

// Custom service for text transformation


app.service('TextService', function() {
this.toUppercase = function(input) {
return input.toUpperCase();
};

this.toLowercase = function(input) {
return input.toLowerCase();
};
});

app.controller('TextController', function($scope, TextService) {


$scope.inputText = '';
$scope.transformedText = '';

$scope.transformToUppercase = function() {
$scope.transformedText = TextService.toUppercase($scope.inputText);

Department of CS&E, ATMECE, Mysuru.


Angular JS & Node JS – 21CSL581

};

$scope.transformToLowercase = function() {
$scope.transformedText = TextService.toLowercase($scope.inputText);
};
});
</script>
</body>
</html>

Explanation:
In this program:
• We have a text transformation application that allows users to input text.

• We use a custom service, TextService, to transform the text to uppercase and lowercase.
• The TextController handles user interactions and displays the transformed text.

This program demonstrates the use of filters, controllers, and services in the context of a text
transformation application. Users can enter text, and it can be transformed to uppercase or
lowercase.

Output:

Department of CS&E, ATMECE, Mysuru.


Angular JS & Node JS – 21CSL581

Program 6

Build a basic currency converter application that allows users to convert amounts from
one currency to another using a simple exchange rate.
Code:
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<body ng-app="currencyConverterApp">

<div ng-controller="CurrencyConverterController">
<h2>Currency Converter</h2>
<input type="number" ng-model="amount" placeholder="Enter Amount">
<select ng-model="fromCurrency" ng-options="currency for currency in currencies">
</select>
<span> to </span>
<select ng-model="toCurrency" ng-options="currency for currency in currencies">
</select>
<button ng-click="convertCurrency()">Convert</button>

<p>{{ amount }} {{ fromCurrency }} is {{ convertedAmount }} {{ toCurrency }}</p>


</div>

<script>
var app = angular.module('currencyConverterApp', []);

// Custom service for currency conversion


app.service('CurrencyConverterService', function() {
var exchangeRates = {
INR: {
USD: 0.014,
EUR: 0.012,
GBP: 0.011,
JPY: 1.59
},
USD: {
INR: 72.78,
EUR: 0.85,
GBP: 0.74,
JPY: 110.67
},
EUR: {
INR: 83.00,

Department of CS&E, ATMECE, Mysuru.


Angular JS & Node JS – 21CSL581

USD: 1.18,
GBP: 0.88,
JPY: 131.34
},
GBP: {
INR: 92.90,
USD: 1.35,
EUR: 1.14,
JPY: 148.37
},
JPY: {
INR: 0.63,
USD: 0.0090,
EUR: 0.0076,
GBP: 0.0067
}
};

this.convert = function(amount, fromCurrency, toCurrency) {


return amount * exchangeRates[fromCurrency][toCurrency];
};
});

app.controller('CurrencyConverterController', function($scope,
CurrencyConverterService) {
$scope.amount = 1;
$scope.fromCurrency = 'INR'; // Set INR as the default source currency
$scope.toCurrency = 'USD';
$scope.currencies = ['INR', 'USD', 'EUR', 'GBP', 'JPY']; // Add INR as the first item
$scope.convertedAmount = 0;

$scope.convertCurrency = function() {
$scope.convertedAmount = CurrencyConverterService.convert($scope.amount,
$scope.fromCurrency, $scope.toCurrency);
};
});
</script>
</body>
</html>

Explanation:
• We have a currency converter application that allows users to input an amount and
select the source and target currencies.

Department of CS&E, ATMECE, Mysuru.


Angular JS & Node JS – 21CSL581

• We use a custom service, CurrencyConverterService, to perform the currency


conversion based on predefined exchange rates.

• The CurrencyConverterController handles user interactions and displays the


converted amount.

This program demonstrates the use of filters, controllers, and services in the context of a
currency conversion application. Users can enter an amount and select source and target
currencies, and the converted amount is displayed based on predefined exchange rates.

Output:

Department of CS&E, ATMECE, Mysuru.


Angular JS & Node JS – 21CSL581

MODULE-4
Directives & Building Databases: Part-II- Directives – Alternatives to Custom Directives –
Understanding the Basic options – Interacting with Server –HTTP Services – Building
Database, Front End and BackEnd

Program 7
Create a simple AngularJS application with a custom directive for displaying and
interacting with a list of fruits.
Code:
<!DOCTYPE html>

<html ng-app="myApp">
<head>

<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<style>

ul { list-style-type: none; padding: 0; }


li { margin: 5px; cursor: pointer; }

</style>
</head>

<body ng-controller="MainController">
<dynamic-list items="fruits"></dynamic-list>

<script>
angular.module('myApp', [])
.directive('dynamicList', function () {

return {

restrict: 'E',
scope: {

items: '='
},
template: `
<ul>

Department of CS&E, ATMECE, Mysuru.


Angular JS & Node JS – 21CSL581

<li ng-repeat="item in items" ng-click="selectItem(item)">

{{ item }}

</li>
</ul>
`,
link: function (scope, element, attrs) {
scope.selectItem = function (item) {

alert("You selected: " + item);

};
}
};

})
.controller('MainController', function ($scope) {

$scope.fruits = ['Apple', 'Banana', 'Cherry', 'Date', 'Elderberry'];


});

</script>
</body>

</html>

Explanation:

1. AngularJS Setup:
 <html ng-app="myApp">: This sets up an AngularJS application by declaring the
ng-app directive on the <html> element. The application is named "myApp."
 <script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></scri
pt>: This includes the AngularJS library from a CDN, making AngularJS available
for the application.
 <style>: This defines some basic CSS styles used for the list.
2. AngularJS Module and Directive:
 angular.module('myApp', []): Here, we create an AngularJS module named
"myApp" using the angular.module function. This module serves as the container for
the application.
 .directive('dynamicList', function () { ... }: We define a custom directive named
"dynamic-list." This directive restricts it to be used as an element ('E').
3. Directive Template:
 The template property in the directive definition provides the HTML template for the

Department of CS&E, ATMECE, Mysuru.


Angular JS & Node JS – 21CSL581

"dynamic-list" directive. It uses an unordered list (<ul>) and an ng-repeat directive to


iterate through the items in the "fruits" array.
4. Link Function:
 The link function is part of the directive definition. It contains the behavior of the
directive.
 scope.selectItem is a function that gets executed when an item in the list is clicked. It
displays an alert with the selected item's name.
5. Controller:
 .controller('MainController', function ($scope) { ... }: This code defines an
AngularJS controller named "MainController" and injects the $scope service.
 $scope.fruits: The controller initializes an array called "fruits" with some fruit
names.
6. Usage of the Custom Directive:
 <dynamic-list items="fruits"></dynamic-list>: In the HTML body, we use the
"dynamic-list" directive, passing in the "fruits" array as the "items" attribute. This
will render the list of fruits using the custom directive.

In summary, this program creates a simple AngularJS application with a custom directive for
displaying and interacting with a list of fruits. The custom directive makes it easy to create
reusable components within your application, enhancing the modularity and maintainability
of your code.

Output:

Department of CS&E, ATMECE, Mysuru.


Angular JS & Node JS – 21CSL581

Program 8:

A simple AngularJS program that demonstrates the basic CRUD (Create, Read, Update,
Delete) operations using mock data.

Code:
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<title>Simple CRUD App</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body ng-controller="MainController">
<h1>Simple CRUD App</h1>

<!-- Create: Add a new item -->


<form ng-submit="addItem()">
<input type="text" ng-model="newItem" placeholder="Add a new item">
<button type="submit">Add</button>
</form>

<!-- Read: Display items -->


<ul>
<li ng-repeat="item in items">
{{ item }}
<button ng-click="editItem(item)">Edit</button>
<button ng-click="deleteItem(item)">Delete</button>
</li>
</ul>

<!-- Update: Edit an item -->


<div ng-show="isEditing">
<input type="text" ng-model="editedItem" placeholder="Edit item">
<button ng-click="saveEdit()">Save</button>
<button ng-click="cancelEdit()">Cancel</button>
</div>

<script>
var app = angular.module('myApp', []);

app.controller('MainController', function ($scope) {


$scope.items = ['Item 1', 'Item 2', 'Item 3'];

Department of CS&E, ATMECE, Mysuru.


Angular JS & Node JS – 21CSL581

$scope.newItem = '';
$scope.isEditing = false;
$scope.editedItem = '';

$scope.addItem = function () {
if ($scope.newItem) {
$scope.items.push($scope.newItem);
$scope.newItem = '';
}
};

$scope.editItem = function (item) {


$scope.isEditing = true;
$scope.editedItem = item;
$scope.editedItemIndex = $scope.items.indexOf(item);
};

$scope.saveEdit = function () {
if ($scope.editedItem) {
$scope.items[$scope.editedItemIndex] = $scope.editedItem;
$scope.isEditing = false;
$scope.editedItem = '';
}
};

$scope.cancelEdit = function () {
$scope.isEditing = false;
$scope.editedItem = '';
};

$scope.deleteItem = function (item) {


var index = $scope.items.indexOf(item);
if (index !== -1) {
$scope.items.splice(index, 1);
}
};
});
</script>
</body>
</html>

Explanation:

Department of CS&E, ATMECE, Mysuru.


Angular JS & Node JS – 21CSL581

In this example, we have a simple web page with a list of items, and you can perform the
following CRUD operations:

 Create: Add a new item to the list.


 Read: Display the list of items.
 Update: Edit an existing item.
 Delete: Remove an item from the list.

This is a basic AngularJS application that demonstrates the principles of CRUD operations
using mock data.

Output:

Note:
 In this example, we won't use a real backend or a database, but we'll simulate data
manipulation within the AngularJS application.
 In a real-world application, you would replace the mock data with data fetched from a
server and implement API calls for actual database interactions.

Department of CS&E, ATMECE, Mysuru.


Angular JS & Node JS – 21CSL581

MODULE-5

Introduction to NODE .JS: Introduction –Using the Terminals – Editors –Building a Webserver
with Node – The HTTP Module – Views and Layouts.

Introduction:

Node.js is an open-source, cross-platform JavaScript runtime environment that allows you to


run JavaScript code on the server side.
It is built on the V8 JavaScript engine, the same engine that powers Google Chrome, and it
provides a powerful framework for building scalable network applications. Node.js is
commonly used for building web servers, real-time applications, and various server-side
applications.

Using the terminals


Before we get into building a web server with Node.js, let's briefly cover using the terminal.
The terminal is a command-line interface that allows you to interact with your computer and
execute commands. It's an essential tool for working with Node.js.

Here are some basic terminal commands:


• cd: Change directory.
• ls (or dir on Windows): List files and directories.
• mkdir: Create a new directory.
• touch (on Unix-based systems): Create an empty file.
• rm (on Unix-based systems) or del (on Windows): Remove files or directories.
• pwd: Print the current working directory.

Editors
• To write Node.js code, you'll need a text editor or an integrated development
environment (IDE). Some popular choices for writing Node.js code include Visual
Studio Code, Sublime Text, and Atom. These editors provide features like syntax
highlighting, code completion, and debugging tools to make your coding process more
efficient.
Difference Between Node JS and Angular JS
Node.js and AngularJS are two distinct technologies used in web development, but they serve
different purposes and have different roles in a web application.

Node.js AngularJS
Type Node.js is a runtime environment AngularJS (often referred to as
for executing JavaScript code on the "Angular 1") is a JavaScript
server-side. framework for building dynamic web
applications on the client-side.
Department of CS&E, ATMECE, Mysuru.
Angular JS & Node JS – 21CSL581

Use Case: Node.js: It is typically used for AngularJS: It is used on the client-side
server-side programming, enabling to build dynamic, single-page web
the creation of server applications applications (SPAs). AngularJS
and APIs. It's well-suited for provides a framework for creating the
building web servers, real-time user interface and handling client-side
applications, and microservices. application logic.

Server vs. Node.js is used for server-side AngularJS is a client-side framework


Client: development and often works with used for building the user interface
databases and performs server- and handling interactions within web
related tasks like routing, handling applications.
HTTP requests, and server-side
scripting.
Language: Node.js uses JavaScript for server- AngularJS also uses JavaScript, but
side programming. it's specifically designed for building
dynamic web applications.
Development Node.js is often used by backend AngularJS is used by frontend
Role: developers to create server developers to create the user interface
applications and APIs. and manage client-side application
behavior.
Ecosystem: Node.js has a rich ecosystem of AngularJS has its own ecosystem of
packages and libraries available modules and libraries designed for
through npm (Node Package building client-side web applications.
Manager). It's commonly used in
combination with various web
frameworks like Express.js.
Version: Node.js has multiple versions, but AngularJS refers to the first version of
it's typically referred to by its major the Angular framework (Angular 1.x).
version number (e.g., Node.js 14, There are subsequent versions known
Node.js 16, etc.). as Angular 2 and onwards.
Evolution: Node.js has evolved to become a AngularJS (1.x) has been largely
versatile server-side runtime, and succeeded by Angular (2+), which is a
complete rewrite of the framework

it's widely used in web and offers enhanced capabilities and


development. performance.

Department of CS&E, ATMECE, Mysuru.


Angular JS & Node JS – 21CSL581

How to run the programs?


To run Node.js programs, follow these steps:
1. Install Node.js: If you haven't already, you need to install Node.js on your computer.
You can download the installer for your specific operating system (Windows, macOS,
or Linux) from the official Node.js website: https://nodejs.org
2. Write Your Node.js Code: Use a text editor or integrated development environment
(IDE) to write your Node.js code. Save the code with a .js file extension, e.g.,
myprogram.js.
3. Open the Terminal or Command Prompt:
• On Windows, you can use the Command Prompt or PowerShell.
• On macOS and Linux, you can use the Terminal.
4. Navigate to the Directory with Your Node.js File:
Use the cd command to navigate to the directory where your Node.js file is located.
Example (on macOS and Linux):
cd /path/to/your/project/directory

Example (on Windows in Command Prompt):


cd C:\path\to\your\project\directory

5. Run Your Node.js Program:


To run a Node.js program, simply type node followed by the name of your JavaScript
file.
Example:
node myprogram.js

Note: Replace myprogram.js with the actual name of your JavaScript file.

Department of CS&E, ATMECE, Mysuru.


Angular JS & Node JS – 21CSL581

Sample Program:
Write a simple Node.js program that reads a text file and prints its contents to the console.
Description: You can create a text file with some content in the same directory as this script
and then run it to see the contents of the file displayed in the console.

Step 1: Create a text file named sample.txt with some text content. For example, you can
create a file with the following text:
Hello, Node.js!

This is a sample text file.


Welcome to Node.js programming.

Step 2: Create a Node.js program, let's name it readFile.js, with the following code:

readFile.js

// Import the 'fs' (File System) module


const fs = require('fs');

// Read the content of 'sample.txt' file


fs.readFile('sample.txt', 'utf8', (err, data) => {
if (err) {
console.error('Error reading the file:', err);
return;
}

// Print the file content to the console


console.log('File content:');
console.log(data);
});

Step 3: Open your terminal or command prompt, navigate to the directory where both
sample.txt and readFile.js are located, and run the Node.js program:

node readFile.js

Department of CS&E, ATMECE, Mysuru.


Angular JS & Node JS – 21CSL581

Output:

Department of CS&E, ATMECE, Mysuru.


Angular JS & Node JS – 21CSL581

Program 9:
A simple Node.js program that creates a basic HTTP server and responds with "Hello,
Node.js!" when you access it through a web browser.
Step 1: Create a new JavaScript file, let's call it simpleServer.js, with the following code.

Code:
// Import the 'http' module
const http = require('http');

// Create an HTTP server


const server = http.createServer((req, res) => {

// Set the response header


res.writeHead(200, { 'Content-Type': 'text/plain' });

// Send the response to the client


res.end('Hello, Node.js!\n');
});

// Listen on port 3000


const port = 3000;

server.listen(port, 'localhost', () => {

console.log(`Server is running at http://localhost:${port}/`);


});

Step 2: Open your terminal or command prompt, navigate to the directory where
simpleServer.js is located, and run the Node.js program.

node simpleServer.js
Output:
You should see the message "Server is running at http://localhost:3000/" in the terminal,
indicating that the server is running.

Department of CS&E, ATMECE, Mysuru.


Angular JS & Node JS – 21CSL581

Now, open a web browser and visit http://localhost:3000/. You should see a simple webpage
displaying "Hello, Node.js!" in your browser.

Note: You can stop the server by pressing Ctrl + C in your terminal.

Building a web server:


Building a web server with Node.js allows you to handle HTTP requests and serve web content.
This concept is fundamental for creating web applications, APIs, and serving web pages.
Node.js provides the necessary modules to create a web server, and Express.js, a popular
framework, simplifies the process.
How to build a web server with Node.js?

1. Setting Up Node.js: First, make sure you have Node.js installed. If not, you can
download it from the official website: https://nodejs.org.
2. Creating a Server: To create a web server in Node.js, you typically use the built-in
http module. However, many developers prefer using Express.js, a web application
framework that simplifies server creation and routing.

3. Handling HTTP Requests: Define routes to handle various HTTP requests (GET,
POST, PUT, DELETE, etc.) from clients. These routes are associated with specific
URL paths and define how your server responds to different requests.

4. Serving Content: You can serve HTML, JSON, static files (like CSS and images), and
more. You set the appropriate response headers and send the content back to the client.

Department of CS&E, ATMECE, Mysuru.


Angular JS & Node JS – 21CSL581

Program 10
Write a program which demonstrates the basic concept of building a web server with
Node.js using Express.js.
Description: This example demonstrates the basic concept of building a web server with
Node.js using Express.js. You can expand this server by defining more routes, serving HTML
pages, handling POST requests, and building more complex web applications.
Install Express.js if you haven't already by running “npm install express” in your project
directory.

Step 1:

1. Install Express.js if you haven't already by running npm install express in your
project directory.

Note: You should ensure that “npm” operates within a directory where you have the
necessary permissions (Preferably other than C Drive).

2. Create a JavaScript file, let's call it webServer.js, and add the following code:
const express = require('express');
const app = express();
const port = 3000;

// Define a route for the root URL


app.get('/', (req, res) => {
res.send('Hello, this is your Node.js web server!');

});
// Start the server
app.listen(port, () => {

console.log(`Server is running on http://localhost:${port}`);


});

Department of CS&E, ATMECE, Mysuru.


Angular JS & Node JS – 21CSL581

Explanation:
In this code:

• We require the Express.js module.

• We create an instance of an Express application.


• We define a route for the root URL (/) and send a simple text response.
• We start the server on port 3000.

Step 3: Open your terminal, navigate to the directory where webServer.js is located,
and run the Node.js program.
node webServer.js

You should see the message "Server is running on http://localhost:3000" in the terminal.

Open a web browser and visit http://localhost:3000/. You'll see the text "Hello, this is your
Node.js web server!" displayed in your browser.

Output:

Department of CS&E, ATMECE, Mysuru.


Angular JS & Node JS – 21CSL581

Program 11:
Write an application-oriented Node.js program that fetches data from a public API and
displays it in your console.
Note: In this example, we'll use the JSONP laceholder API to retrieve a list of posts.

Step 1: First, make sure you have Node.js installed on your system. If you don't have it, you
can download it from the official website: https://nodejs.org.

Step 2: Create a new JavaScript file, let's call it fetchPosts.js, and add the following code:
const axios = require('axios');

// Define the URL of the JSONPlaceholder API


const apiURL = 'https://jsonplaceholder.typicode.com/posts';

// Function to fetch and display posts


async function fetchPosts() {
try {

const response = await axios.get(apiURL);


const posts = response.data;

console.log('List of Posts:');
posts.forEach((post) => {
console.log(`Title: ${post.title}`);

console.log(`Body: ${post.body}\n`);

});
} catch (error) {

console.error('Error fetching data:', error.message);


}
}

// Call the function to fetch and display posts


fetchPosts();
Explanation:

Department of CS&E, ATMECE, Mysuru.


Angular JS & Node JS – 21CSL581

In this code:

• We use the Axios library to make an HTTP GET request to the JSONPlaceholder API
(https://jsonplaceholder.typicode.com/posts) to retrieve a list of posts.

• The fetchPosts function is an asynchronous function that fetches the data and displays
the titles and bodies of the posts in the console.
Step 3: Navigate to the directory where your Node.js program (in this case, fetchPosts.js) is
located. You should run the following commands from the directory where your JavaScript
file is. Run the following command to install 'axios':

npm install axios

Step 4: After the installation is complete, you can run your Node.js program again using the
following command:

node fetchPosts.js

Department of CS&E, ATMECE, Mysuru.


Angular JS & Node JS – 21CSL581

Output:

Department of CS&E, ATMECE, Mysuru.


Angular JS & Node JS – 21CSL581

HTTP Module:
The HTTP module in Node.js allows you to create HTTP servers and handle HTTP requests.
It provides functions for handling HTTP requests and responses. Using the HTTP module, you
can create a web server that listens for incoming HTTP requests and responds to them.

Program 5:

Write a simple example of creating an HTTP server using the HTTP module in Node.js
Code:
const http = require('http');

// Create an HTTP server


const server = http.createServer((req, res) => {

res.writeHead(200, { 'Content-Type': 'text/plain' });


res.end('Hello, Node.js HTTP Server!');

});

// Define the port and host


const port = 3000;
const host = '127.0.0.1';

// Start the server


server.listen(port, host, () => {

console.log(`Server is running at http://${host}:${port}/`);


});

Explanation:
In this code:
1. We import the HTTP module using const http = require('http').

2. We create an HTTP server using http.createServer. It takes a callback function that is


called for each incoming HTTP request. In this example, we simply respond with
"Hello, Node.js HTTP Server!".

3. We set the HTTP response header using res.writeHead to indicate a successful


response with a content type of "text/plain".
4. We send the response content using res.end.

Department of CS&E, ATMECE, Mysuru.


Angular JS & Node JS – 21CSL581

5. We specify the port and host on which the server will listen. In this case, it's listening
on port 3000 and the local host ('127.0.0.1').

6. Finally, we start the server using server.listen. The callback function logs a message
to the console when the server starts.

Output:
To run this program, save it to a JavaScript file (e.g., httpServer.js) and execute it using the
node command:

node httpServer.js

Open http://localhost:3000 in your browser

Department of CS&E, ATMECE, Mysuru.


Angular JS & Node JS – 21CSL581

Views and Layouts:


Views and layouts are fundamental concepts in web development that allow you to separate
the structure and content of your web pages. In Node.js applications, you typically use a
templating engine like EJS to create views and layouts. Views represent the content of
individual pages, while layouts define the common structure for your web pages, such as the
header and footer.

Program 12
Write a simple program that illustrates the use of views and layouts in a Node.js
application using the EJS templating engine.
Step 1: First, make sure you have Node.js installed on your system. If you don't have it, you
can download it from the official website: https://nodejs.org.
Step 2: Create a new directory for your project and navigate to it in your terminal.

Step 3: Initialize a new Node.js project and install the required dependencies. Run the
following commands:

npm init -y
npm install express ejs

Department of CS&E, ATMECE, Mysuru.


Angular JS & Node JS – 21CSL581

Step 4: Create a new file, app.js, and add the following code:
const express = require('express');
const app = express();

const port = 3000;

// Set EJS as the view engine


app.set('view engine', 'ejs');

// Define a route to render a view


app.get('/', (req, res) => {
res.render('index', { title: 'Welcome to My Website' });
});

// Start the server


app.listen(port, () => {

console.log(`Server is running on http://localhost:${port}`);


});

Step 5: Create a views directory in your project folder.

Inside the views directory, create an EJS template file named index.ejs with the
following content:
<!DOCTYPE html>

<html>
<head>
<title><%= title %></title>

</head>
<body>
<header>

<h1><%= title %></h1>


</header>

Department of CS&E, ATMECE, Mysuru.


Angular JS & Node JS – 21CSL581

<main>
<p>This is the main content of the page.</p>

</main>

<footer>
<p>&copy; 2023 My Website</p>
</footer>
</body>

</html>

Explanation:
In this program:
• We use Express.js as the web framework.
• We set the view engine to EJS using app.set('view engine', 'ejs').
• There's a single route that renders the index.ejs view and passes a title variable to it.

• The index.ejs view is an EJS template that includes placeholders (<%= title %>) for
dynamic data. The title variable is passed from the route.

• When you access the root URL (http://localhost:3000), the EJS template is rendered,
and the dynamic title is displayed.
Step 6: To See the output

Run the Node.js application:


node app.js

Open a web browser and navigate to http://localhost:3000 to see the rendered view with
a layout. The layout includes a header and footer, and the content is dynamically
populated with the title provided in the route.

Department of CS&E, ATMECE, Mysuru.


Angular JS & Node JS – 21CSL581

Output:

Department of CS&E, ATMECE, Mysuru.

You might also like