0% found this document useful (0 votes)
28 views40 pages

Angular Js Chapter

Uploaded by

kelseabih20
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
28 views40 pages

Angular Js Chapter

Uploaded by

kelseabih20
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 40

Course : Introduction to AngularJS

Course Description:
This course provides an in-depth understanding of AngularJS, a powerful JavaScript framework
for building dynamic web applications. Students will learn the fundamentals of AngularJS,
including data binding, directives, controllers, services, and routing. The course will also cover
advanced topics like form validation, dependency injection, and working with external APIs.
Through hands-on examples and projects, students will gain the skills necessary to build robust and
interactive web applications using AngularJS.
Course Syllabus:
1. Introduction to AngularJS
 What is AngularJS and its features
 Setting up AngularJS in your project
 Basic AngularJS application structure
 AngularJS expressions and data binding
 Example: Creating a simple data-bound application
2. Directives and Controllers
 Understanding directives and their role in AngularJS
 Built-in directives (ng-repeat, ng-show, ng-hide, etc.)
 Creating custom directives
 Introduction to controllers and their purpose
 Example: Building a dynamic list using ng-repeat and custom directives
3. Services and Dependency Injection
 Understanding services and their importance
 Built-in services ($http, $location, $routeParams, etc.)
 Creating custom services
 Dependency injection and its benefits
 Example: Implementing a service to fetch data from an API
4. Routing and Single-Page Applications
 Introduction to routing in AngularJS
 Setting up routes and views
 Passing parameters and accessing route data
 Creating a single-page application using AngularJS routing
 Example: Building a multi-page application with navigation using AngularJS routing
5. Form Validation and Error Handling
 Form validation in AngularJS
 Built-in form validation directives (ng-model, ng-required, ng-pattern, etc.)
 Handling form submission and displaying errors
 Custom form validation using directives
 Example: Creating a form with validation and error handling
6. Advanced Topics
 Filters and their usage in AngularJS
 Working with external APIs and AJAX requests
 Implementing authentication and authorization
 Performance optimization techniques
 Example: Integrating an external API to display real-time data in an AngularJS
application
Introduction to AngularJS
1.1 What is AngularJS?

AngularJS is a JavaScript framework developed by Google for building dynamic web applications.
It follows the Model-View-Controller (MVC) architectural pattern and provides a set of powerful
features to simplify web development.

1.2 Features of AngularJS


 Two-way data binding: AngularJS allows automatic synchronization between the model
and the view, making it easy to keep data in sync.
 Directives: AngularJS utilizes directives to extend HTML with new attributes and behaviors,
enabling the creation of reusable components.
 Dependency injection: AngularJS provides a built-in dependency injection system,
allowing for modular and testable code.
 Templating: AngularJS uses HTML templates to define the structure and layout of the
application.
 Routing: AngularJS supports client-side routing, enabling the creation of single-page
applications.

1.3 Setting up AngularJS

To start using AngularJS, follow these steps:


Step 1: Include the AngularJS library in your HTML file using the <script> tag:

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

<script src="../js/angular.min.js.js"></script>

Step 2: Create an AngularJS application module using the angular.module() function:

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

Step 3: Add the ng-app directive to the root element of your HTML to bootstrap the AngularJS
application:
html
<html ng-app="myApp">

1.4 AngularJS Expressions and Data Binding

AngularJS expressions are written inside double curly braces {{ }} and can be used to bind data
to HTML elements. For example:
html
<div ng-app="myApp">
<h1>{{ message }}</h1>
</div>

In the above example, the message variable is bound to the <h1> element, and any changes to the
variable will automatically update the view.
Example: Creating a simple data-bound application
Let's create a simple AngularJS application that displays a message based on user input.
HTML:
html
<div ng-app="myApp">
<input type="text" ng-model="name" placeholder="Enter your name">
<p>Welcome, {{ name }}!</p>
</div>

Explanation:
 We define an AngularJS module named myApp.
 Inside the module, we have an input element with the ng-model directive, which binds
the input value to the name variable.
 The paragraph element displays a welcome message using the {{ name }} expression.

You can try entering your name in the input field, and the welcome message will be updated in real-
time.

Directives and Controllers


In this section, we will dive into directives and controllers, two essential components of AngularJS
that help in creating dynamic and interactive web applications.

2.1 Understanding Directives


Directives are markers on a DOM element that tell AngularJS to attach specific behaviors or
manipulate the element. They allow you to extend HTML with new attributes and create reusable
components.

2.2 Built-in Directives


AngularJS provides a set of built-in directives that you can use out of the box.
Some commonly used directives include:
 ng-repeat: Loops over a collection and generates HTML elements for each item.
 ng-show and ng-hide: Conditionally shows or hides elements based on an expression.
 ng-click: Binds a click event to a function in the controller.

 ng-if: it is used to conditionally show or hide elements based on a given expression. It is


a powerful tool for controlling the visibility of elements dynamically

Let's say we have a simple scenario where we want to display a message based on a condition.
Here's an example:

html
<div ng-app="myApp" ng-controller="MyController">
<button ng-click="toggleMessage()">Toggle Message</button>

<div ng-if="showMessage">
<h2>Welcome to the Course!</h2>
<p>This is an introductory course on AngularJS.</p>
</div>
</div>

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

app.controller('MyController', function($scope) {
$scope.showMessage = false;

$scope.toggleMessage = function() {
$scope.showMessage = !$scope.showMessage;
};
});
</script>

In the above example, we have an AngularJS application with a controller named "MyController".
Inside the controller, we define a variable called showMessage and initialize it as false.

In the HTML code, we have a button with the ng-click directive, which calls the toggleMes-
sage function when clicked.

Inside the div element with the ng-if directive, we specify the condition showMessage. If
showMessage is true, the contents inside the div will be rendered. If showMessage is false, the
contents will not be rendered.

Initially, the message is hidden because showMessage is set to false. When we click the "Toggle
Message" button, the toggleMessage function is triggered, and it toggles the value of showMessage
between true and false. As a result, the message will be shown or hidden accordingly.

The ng-if directive is useful when you want to conditionally display elements based on user inter-
actions, data availability, or any other dynamic conditions in your application.

Example: Building a dynamic list using ng-repeat and custom directives


Let's create a dynamic list using the ng-repeat directive.

HTML:
<div ng-app="myApp" ng-controller="myController">
<ul>
<li ng-repeat="item in items">{{ item }}</li>
</ul>
</div>

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

app.controller('myController', function($scope) {
$scope.items = ['Apple', 'Banana', 'Orange'];
});
</script>

Explanation:
 We define an AngularJS module named myApp and attach a controller named
myController to it.
 Inside the controller, we have a $scope object that holds the data for our application.
 The ng-repeat directive iterates over the items array and generates an <li> element
for each item.
Now, when you run this application, you'll see a list containing the items "Apple," "Banana," and
"Orange."

2.3 Creating Custom Directives


AngularJS also allows you to create custom directives to encapsulate reusable behaviors or
UI components. Custom directives are defined using the app.directive() method.

Example: Creating a custom directive to display a tooltip

Let's create a custom directive called myTooltip that displays a tooltip when the user hovers over
an element.
HTML:
<div ng-app="myApp">
<button my-tooltip="Click me!" tooltip-text="This is a tooltip.">
Hover over me
</button>
</div>

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

app.directive('myTooltip', function() {
return {
restrict: 'A',
scope: {
tooltipText: '@'
},
link: function(scope, element, attrs) {
var tooltip = document.createElement('div');
tooltip.textContent = scope.tooltipText;
tooltip.className = 'tooltip';

element.on('mouseenter', function() {
document.body.appendChild(tooltip);
});

element.on('mouseleave', function() {
document.body.removeChild(tooltip);
});
}
};
});
</script>

Explanation:
 We define an AngularJS module named myApp.
 The myTooltip directive is created using the app.directive() method. It takes two
attributes: tooltip-text and my-tooltip.
 The restrict: 'A' option restricts the directive to be used as an attribute.
 The scope property defines an isolated scope for the directive, and we bind the
tooltipText attribute to the directive's scope using the @ symbol.
 The link function contains the logic for creating and removing the tooltip element.

When you hover over the "Hover over me" button, a tooltip with the text "This is a tooltip" will
appear.

Services and Dependency Injection


In this section, we will explore services in AngularJS and learn how to utilize dependency
injection to create modular and maintainable code.

3.1 Understanding Services

Services in AngularJS are singleton objects that provide specific functionality and can be injected
into other components like controllers, directives, or even other services. They are used to
encapsulate reusable logic and data.

3.2 Built-in Services

AngularJS provides a set of built-in services that cover common tasks. Some commonly used built-
in services include:
 $http: Used for making HTTP requests to a server.
 $location: Provides access to the current URL and allows for URL manipulation.
 $routeParams: Retrieves parameters from the current route.
3.3 Creating Custom Services

AngularJS allows you to create your own custom services


using the app.service() or app.factory() methods.

Example: Implementing a service to fetch data from an API


Let's create a custom service called userService that fetches user data from an API.

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

app.service('userService', function($http) {
this.getUser = function(userId) {
return $http.get('/api/users/' + userId);
};
});

app.controller('myController', function($scope, userService) {


userService.getUser(123)
.then(function(response) {
$scope.user = response.data;
})
.catch(function(error) {
console.error('Error fetching user:', error);
});
});
</script>

Explanation:
 We define an AngularJS module named myApp.
 The userService service is created using the app.service() method. It takes the
$http service as a dependency and provides a getUser() method that makes an HTTP
GET request to fetch user data.
 In the controller, we inject the userService and use it to fetch a user with the ID 123.
 The retrieved user data is assigned to the $scope.user variable.

When this code runs, it will fetch user data from the API and assign it to the $scope.user
variable, making it available for display in the view.

3.4 Dependency Injection

Dependency injection is a design pattern used in AngularJS to ensure that components are loosely
coupled and easily testable. It allows you to declare dependencies for a component and have them
automatically injected.
AngularJS uses the $injector service to handle dependency injection. Dependencies are
declared in the function's argument list.
For example, in the previous code snippet, we injected the $http service into the userService
service and the userService into the myController controller.

Application Exercises

Exercise 1: Todo List Application

Create a simple todo list application using AngularJS. The application should have the
following features:
 Display a list of tasks.
 Allow users to add new tasks.
 Allow users to mark tasks as completed.
 Provide a count of the total number of tasks.
Hint: Use a custom directive for displaying each task, a controller to manage the tasks, and a service
to handle the task data.
Exercise 2: Weather App
Build a weather application that fetches weather data from an API and displays it to the user. The
application should have the following features:
 Allow users to enter a location and retrieve weather information.
 Display the current temperature, weather conditions, and a brief description.
 Provide a five-day forecast.
Hint: Use a service to handle the API request and retrieve weather data, a controller to manage the
user input and data binding, and a custom directive to display the weather information.
Exercise 3: Image Gallery
Develop an image gallery application that fetches a collection of images from an API and displays
them in a grid. The application should have the following features:
 Fetch a collection of images from an API.
 Display the images in a grid layout.
 Allow users to filter images by category or search for specific images.
 Implement pagination to handle large image collections.
Hint: Use a service to handle the API request and retrieve image data, a controller to manage the
filtering and pagination logic, and a custom directive to display the images in a grid layout.
These exercises will help you practice using services, dependency injection, directives, and
controllers in real-world scenarios. You can start with one exercise at a time and gradually build
upon it, adding more functionality and refining the user experience.

Exercise 1: Todo List Application


1. HTML Markup:
<div ng-app="todoApp" ng-controller="TodoController">
<input type="text" ng-model="newTask" placeholder="Enter a new task">
<button ng-click="addTask()">Add Task</button>
<ul>
<li ng-repeat="task in tasks">
<span ng-class="{completed: task.completed}">{{ task.name }}</span>
<button ng-click="markCompleted(task)">Mark Completed</button>
</li>
</ul>
<p>Total Tasks: {{ tasks.length }}</p>
</div>

 JavaScript:
<script>
var app = angular.module('todoApp', []);

app.controller('TodoController', function($scope, taskService) {


$scope.tasks = taskService.getTasks();

$scope.addTask = function() {
taskService.addTask($scope.newTask);
$scope.newTask = '';
};

$scope.markCompleted = function(task) {
taskService.markCompleted(task);
};
});

app.service('taskService', function() {
var tasks = [
{ name: 'Task 1', completed: false },
{ name: 'Task 2', completed: true },
{ name: 'Task 3', completed: false }
];

this.getTasks = function() {
return tasks;
};

this.addTask = function(taskName) {
tasks.push({ name: taskName, completed: false });
};

this.markCompleted = function(task) {
task.completed = true;
};
});
</script>

Explanation:
1. We define an AngularJS module named 'todoApp', which will be used as the container
for our application.
2. The TodoController is created using the app.controller() method. It takes the
$scope and taskService as dependencies.
3. In the HTML markup, we bind the input field to the $scope.newTask variable using
ng-model. This allows us to get the user input.
4. When the "Add Task" button is clicked, the addTask() function is executed. It calls the
addTask() function in the taskService to add the new task to the tasks array.
5. The ng-repeat directive is used to iterate over the tasks array and display each task in
a list item.
6. The "Mark Completed" button triggers the markCompleted() function, which marks the
task as completed by updating its completed property in the taskService.
7. The taskService is created using the app.service() method. It contains the
getTasks(), addTask(), and markCompleted() functions to manage the tasks.
8. Initially, the tasks array in the taskService contains three predefined tasks.
9. The getTasks() function returns the tasks array to the TodoController, which
binds it to the $scope.tasks variable.
10. The total number of tasks is displayed using {{ tasks.length }}.

Exercise 2: Weather App


1. HTML Markup:
<div ng-app="weatherApp" ng-controller="WeatherController">
<input type="text" ng-model="location" placeholder="Enter a location">
<button ng-click="getWeather()">Get Weather</button>
<div ng-if="weatherData">
<h2>{{ weatherData.name }}</h2>
<p>Temperature: {{ weatherData.main.temp }}°C</p>
<p>Weather: {{ weatherData.weather[0].description }}</p>
</div>
</div>

 JavaScript:
<script>
var app = angular.module('weatherApp', []);

app.controller('WeatherController', function($scope, weatherService) {


$scope.getWeather = function() {
weatherService.getWeather($scope.location)
.then(function(response) {
$scope.weatherData = response.data;
})
.catch(function(error) {
console.error('Error fetching weather data:', error);
});
};
});

app.service('weatherService', function($http) {
this.getWeather = function(location) {
var apiKey = 'YOUR_API_KEY';
var apiUrl = 'https://api.openweathermap.org/data/2.5/weather';

var config = {
params: {
q: location,
appid: apiKey,
units: 'metric'
}
};

return $http.get(apiUrl, config);


};
});
</script>

Explanation:
1. We define an AngularJS module named 'weatherApp' as the container forour
application.
2. The WeatherController is created using the app.controller() method. It takes
the $scope and weatherService as dependencies.
3. In the HTML markup, we bind the input field to the $scope.location variable using
ng-model. This allows us to get the user's location input.
4. When the "Get Weather" button is clicked, the getWeather() function is executed. It
calls the getWeather() function in the weatherService to fetch the weather data for
the provided location.
5. The weatherService is created using the app.service() method. It takes the
$http service as a dependency to make the API request.
6. The getWeather() function in the weatherService constructs the API URL and
parameters, and then makes an HTTP GET request using the $http service.
7. The response from the API is returned to the getWeather() function in the
WeatherController, which assigns it to the $scope.weatherData variable.
8. The weather data is then displayed in the HTML using {{ weatherData.name }}, {{
weatherData.main.temp }}°C, and
{{ weatherData.weather[0].description }}.

Exercise 3: Image Gallery


1. HTML Markup:
<div ng-app="imageGalleryApp" ng-controller="ImageGalleryController">
<input type="text" ng-model="searchTerm" placeholder="Search images">
<div ng-repeat="image in images | filter:searchTerm">
<img ng-src="{{ image.url }}" alt="{{ image.title }}">
<p>{{ image.title }}</p>
</div>
</div>

 JavaScript:
<script>
var app = angular.module('imageGalleryApp', []);

app.controller('ImageGalleryController', function($scope, imageService)


{
$scope.images = [];

$scope.searchTerm = '';

imageService.getImages()
.then(function(response) {
$scope.images = response.data;
})
.catch(function(error) {
console.error('Error fetching images:', error);
});
});

app.service('imageService', function($http) {
this.getImages = function() {
var apiUrl = 'https://api.example.com/images';

return $http.get(apiUrl);
};
});
</script>

Explanation:
1. We define an AngularJS module named 'imageGalleryApp' as the container for our
application.
2. The ImageGalleryController is created using the app.controller() method. It
takes the $scope and imageService as dependencies.
3. In the HTML markup, we bind the input field to the $scope.searchTerm variable using
ng-model. This allows us to filter the images based on the user's search input.
4. The ng-repeat directive is used to iterate over the images array and display each image
along with its title.
5. The imageService is created using the app.service() method. It takes the $http
service as a dependency to make the API request.
6. The getImages() function in the imageService makes an HTTP GET request to
retrieve the images from the API and returns the response.
7. In the ImageGalleryController, the getImages() function is called when the
controller is initialized. The images returned from the API are assigned to the
$scope.images variable.
8. The images are displayed in the HTML using ng-repeat and {{ image.url }} for
the image source and {{ image.title }} for the image title.

These exercises provide practical examples of how to use services, dependency injection, directives,
and controllers in AngularJS applications. Remember to replace 'YOUR_API_KEY' with your
own API key in the Weather App exercise.

Exercise 4: Quiz Application


1. HTML Markup:

<div ng-app="quizApp" ng-controller="QuizController">


<h2>{{ currentQuestion.question }}</h2>
<ul>
<li ng-repeat="choice in currentQuestion.choices" ng-
click="checkAnswer(choice)">
{{ choice }}
</li>
</ul>
<p>Score: {{ score }}</p>
</div>
 JavaScript:
<script>
var app = angular.module('quizApp', []);

app.controller('QuizController', function($scope, quizService) {


$scope.score = 0;
$scope.currentQuestionIndex = 0;
$scope.currentQuestion =
quizService.getQuestion($scope.currentQuestionIndex);

$scope.checkAnswer = function(choice) {
if (choice === $scope.currentQuestion.correctAnswer) {
$scope.score++;
}
$scope.currentQuestionIndex++;
$scope.currentQuestion =
quizService.getQuestion($scope.currentQuestionIndex);
};
});

app.service('quizService', function() {
var questions = [
{
question: 'What is the capital of France?',
choices: ['London', 'Paris', 'Berlin', 'Rome'],
correctAnswer: 'Paris'
},
{
question: 'Who painted the Mona Lisa?',
choices: ['Leonardo da Vinci', 'Pablo Picasso', 'Vincent van
Gogh', 'Michelangelo'],
correctAnswer: 'Leonardo da Vinci'
},
// Add more questions here
];

this.getQuestion = function(index) {
return questions[index];
};
});
</script>

Explanation:
1. We define an AngularJS module named 'quizApp' as the container for our application.
2. The QuizController is created using the app.controller() method. It takes the
$scope and quizService as dependencies.
3. In the HTML markup, we display the current question using
{{ currentQuestion.question }} and the choices using ng-repeat and
{{ choice }}.
4. When a choice is clicked, the checkAnswer() function is executed. It compares the
selected choice with the correct answer of the current question. If the answer is correct, the
score is incremented.
5. After checking the answer, the currentQuestionIndex is incremented, and the
currentQuestion is updated with the next question using the quizService.
6. The quizService is created using the app.service() method. It contains an array of
questions, each with a question, choices, and correct answer.
7. The getQuestion() function in the quizService retrieves a question from the
questions array based on the provided index.

Exercise 5: Authentication System


1. HTML Markup:
<div ng-app="authApp" ng-controller="AuthController">
<form ng-submit="login()">
<input type="text" ng-model="username" placeholder="Username">
<input type="password" ng-model="password" placeholder="Password">
<button type="submit">Login</button>
</form>
<p ng-if="isLoggedIn">Welcome, {{ username }}!</p>
</div>

 JavaScript:
<script>
var app = angular.module('authApp', []);

app.controller('AuthController', function($scope, authService) {


$scope.isLoggedIn = false;

$scope.login = function() {
authService.login($scope.username, $scope.password)
.then(function(response) {
$scope.isLoggedIn = true;
})
.catch(function(error) {
console.error('Login failed:', error);
});
};
});

app.service('authService', function($http) {
this.login = function(username, password) {
var apiUrl = 'https://api.example.com/login';

var data = {
username: username,
password: password
};

return $http.post(apiUrl, data);


};
});
</script>

Explanation:
1. We define an AngularJS module named 'authApp' as the container for our application.
2. The AuthController is created using the app.controller() method. It takes the
$scope and authService as dependencies.
3. In the HTML markup, we bind the input fields to the $scope.username and
$scope.password variables using ng-model. This allows us to get the user's login
credentials.
4. When the login form is submitted, the login() function is executed. It calls the login()
function in the authService to perform the authentication.
5. The authService is created using the

Exercise 4: Quiz Application

1. HTML Markup:
<div>
<h2>Quiz Application</h2>
<div id="question"></div>
<ul id="choices"></ul>
<button id="submit">Submit</button>
<p id="score">Score: <span id="score-value">0</span></p>
</div>

2. JavaScript:
Javascript
var currentQuestion = 0;
var score = 0;

var questions = [
{
question: "What is the capital of France?",
choices: ["London", "Paris", "Berlin", "Rome"],
correctAnswer: "Paris"
},
{
question: "Who painted the Mona Lisa?",
choices: ["Leonardo da Vinci", "Pablo Picasso", "Vincent van Gogh",
"Michelangelo"],
correctAnswer: "Leonardo da Vinci"
}
// Add more questions here
];

function displayQuestion() {
var questionElement = document.getElementById("question");
var choicesElement = document.getElementById("choices");
var submitButton = document.getElementById("submit");

questionElement.textContent = questions[currentQuestion].question;

choicesElement.innerHTML = "";

for (var i = 0; i < questions[currentQuestion].choices.length; i++) {


var choiceElement = document.createElement("li");
choiceElement.textContent = questions[currentQuestion].choices[i];
choiceElement.addEventListener("click", checkAnswer);
choicesElement.appendChild(choiceElement);
}

submitButton.addEventListener("click", nextQuestion);
}

function checkAnswer(event) {
var selectedChoice = event.target.textContent;

if (selectedChoice === questions[currentQuestion].correctAnswer) {


score++;
}
}

function nextQuestion() {
currentQuestion++;

if (currentQuestion === questions.length) {


var scoreElement = document.getElementById("score-value");
scoreElement.textContent = score;

var submitButton = document.getElementById("submit");


submitButton.disabled = true;
} else {
displayQuestion();
}
}

displayQuestion();

Explanation:
1. The HTML markup defines the structure of the quiz application, including a question
element, choices element, submit button, and score element.
2. The JavaScript code initializes the current question index (currentQuestion) and the
score (score) to 0.
3. The questions array contains objects with the question, choices, and correct answer for
each question.
4. The displayQuestion() function retrieves the question and choices for the current
question index and updates the corresponding HTML elements.
5. The checkAnswer() function is called when a choice is clicked. It compares the selected
choice with the correct answer for the current question and increments the score if the
answer is correct.
6. The nextQuestion() function is called when the submit button is clicked. It increments
the current question index and either displays the next question or shows the final score if all
questions have been answered.
7. The displayQuestion() function is initially called to display the first question.

Exercise 5: Authentication System


1. HTML Markup:
<div>
<h2>Authentication System</h2>
<form id="login-form">
<input type="text" id="username" placeholder="Username">
<input type="password" id="password" placeholder="Password">
<button type="submit" id="login-button">Login</button>
</form>
<p id="welcome-message"></p>
</div>

2. JavaScript:
var isLoggedIn = false;
document.getElementById("login-form").addEventListener("submit", function(event)
{
event.preventDefault();

var usernameInput = document.getElementById("username");


var passwordInput = document.getElementById("password");

var username = usernameInput.value;


var password = passwordInput.value;

login(username, password);
});

function login(username, password) {


// Simulating an authentication request
setTimeout(function() {
if (username === "admin" && password === "password") {
isLoggedIn = true;
showWelcomeMessage(username);
} else {
alert("Invalid username or password");
}
}, 1000);
}

function showWelcomeMessage(username) {
var welcomeMessageElement = document.getElementById("welcome-message");
welcomeMessageElement.textContent = "Welcome, " + username + "!";
}

function resetLoginForm() {
var usernameInput = document.getElementById("username");
var passwordInput = document.getElementById("password");

usernameInput.value = "";
passwordInput.value = "";
}

resetLoginForm();

Explanation:
1. The HTML markup defines the structure of the authentication system, including a login
form with username and password inputs, a login button, and a welcome message element.
2. The JavaScript code initializes the isLoggedIn variable to false.
3. The login() function is called when the

Routing and Single-Page Applications


Introduction to Routing in AngularJS:
 Routing allows us to build single-page applications (SPAs) where different views are
loaded dynamically without refreshing the entire page.
 AngularJS provides the ngRoute module to handle routing.
2. Setting up Routes and Views:
 To configure routes, we need to include the ngRoute module and define the routes in
our app.js file.
 Here's an example of setting up routes:
javascript
 app.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/home.html',
controller: 'HomeController'
})
.when('/about', {
templateUrl: 'views/about.html',
controller: 'AboutController'
})
.when('/contact', {
templateUrl: 'views/contact.html',
controller: 'ContactController'
})
.otherwise({
redirectTo: '/'
});
});

 In the above example, we define routes for the home, about, and contact pages. We also set a
default route using the 'otherwise' method.
 Passing Parameters and Accessing Route Data:
 We can pass parameters in the URL and access them in our controllers.
 Here's an example of passing a parameter:
javascript
 app.config(function($routeProvider) {
$routeProvider
.when('/user/:id', {
templateUrl: 'views/user.html',
controller: 'UserController'
});
});

 In the above example, we define a route for the user page with a parameter 'id'. We can
access this parameter in the UserController.
 Creating a Single-Page Application using AngularJS Routing:
 By combining routing with dynamic views, we can create SPAs that provide a seamless user
experience.
 In our HTML, we can use the 'ng-view' directive to specify where the views should be
loaded.
 Here's an example:
html
 <div ng-view></div>
 This will load the corresponding view based on the current route.
Example: Building a Multi-Page Application with Navigation using AngularJS Routing:
 Let's create a multi-page application with a navigation menu using AngularJS routing.
 We'll have different views for home, about, and contact pages.
 Here's an example structure:
- app/
- views/
- home.html
- about.html
- contact.html
- controllers/
- HomeController.js
- AboutController.js
- ContactController.js
- app.js

 In each controller, we can define the necessary functionality for that specific view.
 The HTML files can contain the necessary markup for each page.

Create an AngularJS project using npm and run the app


To create an AngularJS project using npm and run the app, you can follow these steps:

 Open a command prompt or terminal on your machine.


 Navigate to the directory where you want to create your AngularJS project.
 Run the following command to create a new directory for your project:

 mkdir my-angularjs-project

 Change into the newly created directory:

 cd my-angularjs-project

 Now, you can use npm to initialize your project and generate the necessary files. Run the follow-
ing command:

 npm init

This command will prompt you to provide information about your project, such as the name, ver-
sion, description, entry point, etc. You can either press enter to accept the default values or provide
your own.

 After you've completed the initialization process, you can install AngularJS as a dependency.
Run the following command:

 npm install angular@1.8.2

This command will install AngularJS version 1.8.2 in your project. You can modify the version
number as per your requirement.
 Now, let's create an HTML file to serve as the entry point for our AngularJS app. Create a file
named index.html and add the following code:

html
 <!DOCTYPE html>
<html ng-app="myApp">

<head>
<meta charset="utf-8">
<title>My AngularJS App</title>
<script src="node_modules/angular/angular.js"></script>
<script src="app.js"></script>
</head>

<body>
<div ng-controller="MyController">
<h1>{{ welcomeMessage }}</h1>
</div>
</body>

</html>

In this code, we have included the AngularJS script from the node_modules directory and refer-
enced our custom JavaScript file app.js. We have also added a simple AngularJS expression
{{ welcomeMessage }} to display dynamic content.

 Now, let's create the app.js file to define our AngularJS module and controller. Create a file
named app.js and add the following code:

javascript
 var app = angular.module('myApp', []);

app.controller('MyController', function($scope) {
$scope.welcomeMessage = 'Welcome to my AngularJS app!';
});

In this code, we define an AngularJS module named 'myApp' and a controller named 'MyCon-
troller'. The controller sets a value to the $scope.welcomeMessage variable, which will be dis-
played in the HTML.

 Finally, to run the AngularJS app, open the command prompt or terminal and navigate to the root
directory of your project (my-angularjs-project). Run a local server using any server of your
choice. For example, you can use the http-server package, which can be installed globally by
running the following command:

npm install -g http-server

Once installed, run the following command in your project directory:

http-server

The server will start, and you will see a message indicating the server address (e.g.,
http://127.0.0.1:8080). Open your web browser and visit the provided address to see your An-
gularJS app running.
Application

In this example, we will create a multi-page application with navigation using AngularJS
routing. We will have separate views for the home, about, and contact pages. Here's an
example structure for your project:
1. Create the necessary directory structure:
 Create a folder named "app" to hold your application files.
 Inside the "app" folder, create two subfolders named "views" and "controllers".
 The "views" folder will contain the HTML templates for each page, and the
"controllers" folder will hold the JavaScript controllers for each page.
 Create an "app.js" file in the root of the "app" folder to configure the routing.
2. Create the HTML templates:
 Inside the "views" folder, create the following HTML files:
 home.html: This will be the template for the home page.
 about.html: This will be the template for the about page.
 contact.html: This will be the template for the contact page.
 Customize each HTML file with the relevant content for each page.
3. Create the JavaScript controllers:
 Inside the "controllers" folder, create the following JavaScript files:
 HomeController.js: This will be the controller for the home page.
 AboutController.js: This will be the controller for the about page.
 ContactController.js: This will be the controller for the contact page.
 In each controller file, define the necessary functionality for that specific page. For
example:
javascript
 // HomeController.js
app.controller('HomeController', function($scope) {
// Controller logic for the home page
});

// AboutController.js
app.controller('AboutController', function($scope) {
// Controller logic for the about page
});

// ContactController.js
app.controller('ContactController', function($scope) {
// Controller logic for the contact page
});

 Configure the routing in app.js:


 Inside the "app.js" file, configure the routing using the $routeProvider from the ngRoute
module.
 Here's an example of how to set up the routing:
javascript
app.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/home.html',
controller: 'HomeController'
})
.when('/about', {
templateUrl: 'views/about.html',
controller: 'AboutController'
})
.when('/contact', {
templateUrl: 'views/contact.html',
controller: 'ContactController'
})
.otherwise({
redirectTo: '/'
});
});

 In the above code, we define routes for the home, about, and contact pages. The
'templateUrl' property specifies the HTML template to be used, and the 'controller'
property specifies the corresponding controller for each page. The 'otherwise' method is
used to redirect to the home page if the entered URL doesn't match any defined routes.

Form Validation and Error Handling


1. Form Validation in AngularJS:
 AngularJS provides built-in form validation features that help ensure data integrity
and improve the user experience.
 Form validation ensures that the user inputs meet certain criteria before allowing
form submission.
2. Built-in Form Validation Directives:
 AngularJS provides several built-in directives that enable form validation.
 Some commonly used directives include:
 ng-model: Binds the input field to a model variable and tracks its value.
 ng-required: Validates whether the input field is required or not.
 ng-pattern: Validates the input against a regular expression pattern.
 ng-minlength and ng-maxlength: Specify the minimum and maximum length
of the input.
 You can use these directives in combination to create complex validation rules.
3. Handling Form Submission and Displaying Errors:
 When a user submits a form, AngularJS validates the form data based on the defined
validation rules.
 If any validation errors occur, AngularJS automatically adds CSS classes and error
messages to the form elements.
 You can leverage these classes and messages to provide feedback to the user about
the errors.
 You can also disable the form submission until all validation rules are satisfied.
4. Custom Form Validation using Directives:
 AngularJS allows you to create custom directives to implement custom form
validation rules.
 Custom directives provide flexibility in defining complex validation logic.
 You can create a custom directive to validate input fields based on specific
requirements unique to your application.
5. Example: Creating a Form with Validation and Error Handling:
 Let's create an example of a form with validation and error handling.
 Assume we have a registration form with fields for name, email, and password.
 We want to ensure that all fields are filled out and that the email follows a valid
format.
 Here's an example code snippet:
html
<form name="registrationForm" ng-submit="submitForm()" novalidate>
<div>
<label for="name">Name:</label>
<input type="text" id="name" name="name" ng-model="user.name" ng-
required="true">
<div ng-show="registrationForm.name.$error.required">Name is required.</div>
</div>
<div>
<label for="email">Email:</label>
<input type="email" id="email" name="email" ng-model="user.email" ng-
required="true">
<div ng-show="registrationForm.email.$error.required">Email is
required.</div>
<div ng-show="registrationForm.email.$error.email">Invalid email
format.</div>
</div>
<div>
<label for="password">Password:</label>
<input type="password" id="password" name="password" ng-
model="user.password" ng-required="true">
<div ng-show="registrationForm.password.$error.required">Password is
required.</div>
</div>
<button type="submit" ng-disabled="registrationForm.$invalid">Submit</button>
</form>

 In the above example, we use the ng-model directive to bind input fields to the
corresponding model variables.
 The ng-required directive ensures that all fields are filled out.
 The ng-show directive is used to conditionally display error messages based on the
validation status.
 The ng-disabled directive disables the submit button if the form is invalid.
Advanced Topics
1. Filters and Their Usage in AngularJS:

 Filters in AngularJS allow you to format and manipulate data before displaying it in
the UI.
 AngularJS provides built-in filters like currency, date, uppercase, lowercase, etc.
 You can also create custom filters to meet specific formatting requirements.

Suppose we have an array of numbers that we want to display in a formatted manner. We can use
the built-in "currency" filter to achieve this. Here's an example code snippet:
html
<div ng-app="myApp" ng-controller="MyController">
<ul>
<li ng-repeat="number in numbers">{{ number | currency }}</li>
</ul>
</div>

<script>
var app = angular.module('myApp', []);
app.controller('MyController', function($scope) {
$scope.numbers = [1000, 2000, 3000, 4000];
});
</script>

In the above example, we have an AngularJS application with a controller named "MyController".
Inside the controller, we have an array called "numbers" that contains some numerical values.
In the HTML code, we use the ng-repeat directive to iterate over the "numbers" array and display
each number in a list item. We apply the "currency" filter to each number using the '|' pipe symbol.
The "currency" filter formats the number into a currency representation based on the user's locale.
By default, it uses the currency symbol and decimal separators based on the current locale.
When the page is rendered, the numbers will be displayed in the format of the currency used in the
user's locale. For example, if the user's locale is set to the United States, the numbers will be
displayed as $1,000.00, $2,000.00, $3,000.00, $4,000.00.
This is just one example of how you can use filters in AngularJS to format and manipulate data
before displaying it in the UI. AngularJS provides various other built-in filters, such as "uppercase",
"lowercase", "date", etc., and you can also create custom filters to meet specific formatting
requirements.

Working with External APIs and AJAX Requests:


 AngularJS makes it easy to integrate external APIs and retrieve data using AJAX
requests.
 You can use the $http service or the $resource service to make HTTP requests and
handle responses.
 The data received from the API can be bound to the scope variables and displayed in
the UI.
2. Implementing Authentication and Authorization:
 AngularJS provides features to implement authentication and authorization in your
application.
 You can use services like $cookies or $localStorage to store user authentication
tokens or session information.
 Implementing authorization involves controlling access to certain routes or resources
based on user roles or permissions.
3. Performance Optimization Techniques:
 AngularJS applications can benefit from performance optimization techniques.
 Some approaches include:
 Minifying and concatenating JavaScript and CSS files to reduce network
requests.
 Using one-time bindings or the "track by" syntax to optimize two-way data
binding.
 Implementing pagination or lazy loading to reduce the initial load time of
large datasets.
 Using ng-cloak to prevent the display of uncompiled AngularJS templates.
 Avoiding excessive use of watchers and using $watchCollection or
$watchGroup for better performance.
4. Example: Integrating an External API to Display Real-Time Data:
 Let's create an example of integrating an external API to display real-time data in an
AngularJS application.
 Assume we want to display the current weather conditions on a dashboard.
 We will use the OpenWeatherMap API to fetch the weather data.
 Here's an example code snippet:
javascript
app.controller('WeatherController', function($scope, $http) {
$scope.weatherData = {};

$http.get('https://api.openweathermap.org/data/2.5/weather?
q=cityName&appid=YOUR_API_KEY')
.then(function(response) {
$scope.weatherData = response.data;
})
.catch(function(error) {
console.log('Error fetching weather data:', error);
});
});

 In the above example, we define a controller named "WeatherController" and inject the $http
service.
 We use the $http.get method to make a GET request to the OpenWeatherMap API, passing
the desired city name and your API key.
 The response data is stored in the $scope.weatherData variable, which can be bound to the
UI to display the weather information.

Here's a more detailed example of setting up the FastAPI server API and the AngularJS
application for a booking system that interacts with AJAX requests.
FastAPI Server API:
python
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

# Enable CORS
app.add_middleware(
CORSMiddleware,
allow_origins=["http://localhost:4200"], # Replace with your AngularJS
app's URL
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)

# Sample bookings data


bookings = [
{"id": 1, "name": "John Doe", "date": "2022-01-01"},
{"id": 2, "name": "Jane Smith", "date": "2022-01-02"},
]

@app.get("/bookings")
async def get_bookings():
return bookings

@app.post("/bookings")
async def create_booking(booking: dict):
bookings.append(booking)
return booking

@app.put("/bookings/{booking_id}")
async def update_booking(booking_id: int, updated_booking: dict):
for booking in bookings:
if booking["id"] == booking_id:
booking.update(updated_booking)
return booking
return {"error": "Booking not found"}

@app.delete("/bookings/{booking_id}")
async def delete_booking(booking_id: int):
for booking in bookings:
if booking["id"] == booking_id:
bookings.remove(booking)
return {"message": "Booking deleted successfully"}
return {"error": "Booking not found"}

In the above code snippet, we import the necessary modules and set up a FastAPI instance. We also
include CORS middleware to allow requests from the specified AngularJS app's URL.
We define the /bookings endpoint as a GET request to retrieve all bookings, a POST request to
create a new booking, a PUT request to update an existing booking, and a DELETE request to
delete a booking. The sample bookings data is stored in a list.
AngularJS Application:
html
<!DOCTYPE html>
<html ng-app="myApp">

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

<body ng-controller="BookingController">
<h2>Booking App</h2>
<ul>
<li ng-repeat="booking in bookings">{{ booking.name }} -
{{ booking.date }}</li>
</ul>

<form ng-submit="createBooking()">
<input type="text" ng-model="newBooking.name" placeholder="Name" required>
<input type="date" ng-model="newBooking.date" required>
<button type="submit">Create Booking</button>
</form>
<script>
var app = angular.module('myApp', []);

app.controller('BookingController', function($scope, $http) {


$scope.bookings = [];

$http.get('http://localhost:8000/bookings')
.then(function(response) {
$scope.bookings = response.data;
})
.catch(function(error) {
console.log('Error fetching bookings:', error);
});

$scope.createBooking = function() {
$http.post('http://localhost:8000/bookings', $scope.newBooking)
.then(function(response) {
$scope.bookings.push(response.data);
$scope.newBooking = {}; // Clear the form
})
.catch(function(error) {
console.log('Error creating booking:', error);
});
};
});
</script>
</body>

</html>

In the AngularJS application, we include the AngularJS library and set up the application module. In
the controller, we define the $scope.bookings array and use the $http service to make a GET
request to retrieve initial bookings data.
We also define a createBooking function that sends a POST request to create a new booking.
The function is called when the form is submitted. The new booking data is sent in the request body,
and the response data is added to the $scope.bookings array.

Make sure to replace the placeholder URLs (http://localhost:8000/bookings) in both


the FastAPI server code and the AngularJS application with the actual URLs where your FastAPI
server is running.
Problems

Problem 1: E-commerce App


In this exercise, we will create a concrete e-commerce app using AngularJS. The app will consist of
4 pages: Home, Products, Cart, and Checkout. We will walk through each page and explain the
step-by-step process of implementing them.
Step 1: Set Up the AngularJS App
1. Create a new HTML file and name it index.html.
2. Set up the basic structure of the HTML file and include the AngularJS library.
html
<!DOCTYPE html>
<html lang="en" ng-app="ecomApp">
<head>
<meta charset="UTF-8">
<title>E-commerce App</title>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></
script>
</head>
<body>
<div ng-view></div>
</body>
</html>

3. Create a new JavaScript file and name it app.js. This is where we will define the
AngularJS app and configure the routes.
javascript
var app = angular.module("ecomApp", ["ngRoute"]);

app.config(function($routeProvider) {
$routeProvider
.when("/", {
templateUrl: "pages/home.html",
controller: "HomeController"
})
.when("/products", {
templateUrl: "pages/products.html",
controller: "ProductsController"
})
.when("/cart", {
templateUrl: "pages/cart.html",
controller: "CartController"
})
.when("/checkout", {
templateUrl: "pages/checkout.html",
controller: "CheckoutController"
})
.otherwise({
redirectTo: "/"
});
});

Step 2: Create the Home Page


1. Create a new folder named pages in the same directory as index.html.
2. Inside the pages folder, create a new HTML file named home.html. This will be the
template for the Home page.
html
<h1>Welcome to our E-commerce App</h1>
<p>Explore our wide range of products and start shopping!</p>
<a href="#/products">View Products</a>

3. Create a new JavaScript file named homeController.js in the same directory as


index.html. This will be the controller for the Home page.

javascript
app.controller("HomeController", function($scope) {
// Controller logic for the Home page
});

Step 3: Create the Products Page


1. Inside the pages folder, create a new HTML file named products.html. This will be
the template for the Products page.
html
<h1>Our Products</h1>
<!-- Display a list of products -->
<ul>
<li ng-repeat="product in products">{{ product.name }} -
{{ product.price }}</li>
</ul>
<a href="#/cart">Go to Cart</a>

2. Create a new JavaScript file named productsController.js in the same directory as


index.html. This will be the controller for the Products page.

javascript
app.controller("ProductsController", function($scope) {
$scope.products = [
{ name: "Product 1", price: 10 },
{ name: "Product 2", price: 20 },
{ name: "Product 3", price: 30 }
];
});

Step 4: Create the Cart Page


1. Inside the pages folder, create a new HTML file named cart.html. This will be the
template for the Cart page.
html
<h1>Your Cart</h1>
<!-- Display the items in the cart -->
<ul>
<li ng-repeat="item in cart">{{ item.name }} - {{ item.price }}</li>
</ul>
<a href="#/checkout">Proceed to Checkout</a>

2. Create a new JavaScript file named cartController.js in the same directory as


index.html. This will be the controller for the Cart page.

javascript
app.controller("CartController", function($scope) {
// Controller logic for the Cart page
});

Step 5: Create the Checkout Page


1. Inside the pages folder, create a new HTML file named checkout.html. This will be
the template for the Checkout page.
html
<h1>Checkout</h1>
<!-- Display the checkout form -->
<form>
<label for="name">Name:</label>
<input type="text" id="name">
<br>
<label for="address">Address:</label>
<input type="text" id="address">
<br>
<button type="submit">Place Order</button>
</form>

2. Create a new JavaScript file named checkoutController.js in the same directory as


index.html. This will be the controller for the Checkout page.

javascript
app.controller("CheckoutController", function($scope) {
// Controller logic for the Checkout page
});

Step 6: Test the App


1. Open the index.html file in a web browser.
2. The Home page should be displayed by default. Click on the "View Products" link to
navigate to the Products page.
3. On the Products page, you should see a list of products. Click on the "Go to Cart" link to
navigate to the Cart page.
4. On the Cart page, you should see the items you added to the cart. Click on the "Proceed to
Checkout" link to navigate to the Checkout page.
5. On the Checkout page, you should see a form to enter your name and address. Fill in the
form and click the "Place Order" button.
Problem 2: E-Learning App with Chat Integration
In this exercise, we will create a concrete e-learning app with chat integration using
AngularJS. The app will consist of 6 pages: Home, Courses, Course Details, Chat Room, Profile,
and Settings. We will walk through each page and explain the step-by-step process of implementing
them.
Step 1: Set Up the AngularJS App
1. Create a new HTML file and name it index.html.
2. Set up the basic structure of the HTML file and include the AngularJS library.
html
<!DOCTYPE html>
<html lang="en" ng-app="elearningApp">
<head>
<meta charset="UTF-8">
<title>E-Learning App</title>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></
script>
</head>
<body>
<div ng-view></div>
</body>
</html>

3. Create a new JavaScript file and name it app.js. This is where we will define the
AngularJS app and configure the routes.
javascript
var app = angular.module("elearningApp", ["ngRoute"]);

app.config(function($routeProvider) {
$routeProvider
.when("/", {
templateUrl: "pages/home.html",
controller: "HomeController"
})
.when("/courses", {
templateUrl: "pages/courses.html",
controller: "CoursesController"
})
.when("/courses/:courseId", {
templateUrl: "pages/course-details.html",
controller: "CourseDetailsController"
})
.when("/chat", {
templateUrl: "pages/chat.html",
controller: "ChatController"
})
.when("/profile", {
templateUrl: "pages/profile.html",
controller: "ProfileController"
})
.when("/settings", {
templateUrl: "pages/settings.html",
controller: "SettingsController"
})
.otherwise({
redirectTo: "/"
});
});

Step 2: Create the Home Page


1. Create a new folder named pages in the same directory as index.html.
2. Inside the pages folder, create a new HTML file named home.html. This will be the
template for the Home page.
html
<h1>Welcome to our E-Learning App</h1>
<p>Explore our courses and enhance your knowledge!</p>
<a href="#/courses">View Courses</a>

3. Create a new JavaScript file named homeController.js in the same directory as


index.html. This will be the controller for the Home page.

javascript
app.controller("HomeController", function($scope) {
// Controller logic for the Home page
});

Step 3: Create the Courses Page


1. Inside the pages folder, create a new HTML file named courses.html. This will be the
template for the Courses page.
html
<h1>Available Courses</h1>
<!-- Display a list of courses -->
<ul>
<li ng-repeat="course in courses">
<a href="#/courses/{{ course.id }}">{{ course.name }}</a>
</li>
</ul>
<a href="#/chat">Open Chat Room</a>

2. Create a new JavaScript file named coursesController.js in the same directory as


index.html. This will be the controller for the Courses page.

javascript
app.controller("CoursesController", function($scope) {
$scope.courses = [
{ id: 1, name: "Course 1" },
{ id: 2, name: "Course 2" },
{ id: 3, name: "Course 3" }
];
});

Step 4: Create the Course Details Page


1. Inside the pages folder, create a new HTML file named course-details.html. This
will be the template for the Course Details page.
html
<h1>Course Details</h1>
<!-- Display the details of the selected course -->
<p>{{ courseDetails.name }}</p>
<p>{{ courseDetails.description }}</p>

2. Create a new JavaScript file named courseDetailsController.js in the same


directory as index.html. This will be the controller for the Course Details page.

javascript
app.controller("CourseDetailsController", function($scope, $routeParams) {
var courseId = $routeParams.courseId;
// Fetch the course details using the courseId from a database or API
// For simplicity, let's assume we have a hardcoded list of course details
var courseDetailsList = [
{ id: 1, name: "Course 1", description: "This is Course 1" },
{ id: 2, name: "Course 2", description: "This is Course 2" },
{ id: 3, name: "Course3", description: "This is Course 3" }
];

$scope.courseDetails = courseDetailsList.find(function(course) {
return course.id === parseInt(courseId);
});
});

Step 5: Create the Chat Room Page


1. Inside the pages folder, create a new HTML file named chat.html. This will be the
template for the Chat Room page.
html
<h1>Chat Room</h1>
<!-- Display the chat messages -->
<div ng-repeat="message in chatMessages">
<p>{{ message }}</p>
</div>
<!-- Input field for sending messages -->
<input type="text" ng-model="newMessage">
<button ng-click="sendMessage()">Send</button>

2. Create a new JavaScript file named chatController.js in the same directory as


index.html. This will be the controller for the Chat Room page.

javascript
app.controller("ChatController", function($scope) {
$scope.chatMessages = [
"Hello!",
"How are you?",
"Welcome to the chat room!"
];

$scope.sendMessage = function() {
$scope.chatMessages.push($scope.newMessage);
$scope.newMessage = "";
};
});

Step 6: Create the Profile Page


1. Inside the pages folder, create a new HTML file named profile.html. This will be the
template for the Profile page.
html
<h1>User Profile</h1>
<!-- Display user profile details -->
<p>Name: {{ userProfile.name }}</p>
<p>Email: {{ userProfile.email }}</p>

2. Create a new JavaScript file named profileController.js in the same directory as


index.html. This will be the controller for the Profile page.

javascript
app.controller("ProfileController", function($scope) {
// Fetch the user profile details from a database or API
// For simplicity, let's assume we have a hardcoded user profile
$scope.userProfile = {
name: "John Doe",
email: "john@example.com"
};
});

Step 7: Create the Settings Page


1. Inside the pages folder, create a new HTML file named settings.html. This will be
the template for the Settings page.
html
<h1>Settings</h1>
<!-- Display settings options -->
<p>Choose your preferred language:</p>
<select ng-model="selectedLanguage">
<option value="en">English</option>
<option value="es">Spanish</option>
<option value="fr">French</option>
</select>

2. Create a new JavaScript file named settingsController.js in the same directory as


index.html. This will be the controller for the Settings page.

javascript
app.controller("SettingsController", function($scope) {
// Fetch the user's selected language from a database or API
// For simplicity, let's assume the default language is English
$scope.selectedLanguage = "en";
});

Congratulations! You have successfully created a concrete e-learning app with chat integration
using AngularJS. Each page has been implemented with their respective templates and controllers.
Exercise: Restaurant and Hotel Booking App with Chat Integration
In this case, we will create a concrete restaurant and hotel booking app with chat integration
using AngularJS. The app will consist of 10 pages: Home, Restaurants, Restaurant Details, Hotel,
Hotel Details, Booking, Booking Details, Chat Room, Profile, and Settings. We will walk through
each page and explain the step-by-step process of implementing them.
Step 1: Set Up the AngularJS App
1. Create a new HTML file and name it index.html.
2. Set up the basic structure of the HTML file and include the AngularJS library.
html
<!DOCTYPE html>
<html lang="en" ng-app="bookingApp">
<head>
<meta charset="UTF-8">
<title>Restaurant and Hotel Booking App</title>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></
script>
</head>
<body>
<div ng-view></div>
</body>
</html>

3. Create a new JavaScript file and name it app.js. This is where we will define the
AngularJS app and configure the routes.
javascript
var app = angular.module("bookingApp", ["ngRoute"]);

app.config(function($routeProvider) {
$routeProvider
.when("/", {
templateUrl: "pages/home.html",
controller: "HomeController"
})
.when("/restaurants", {
templateUrl: "pages/restaurants.html",
controller: "RestaurantsController"
})
.when("/restaurants/:restaurantId", {
templateUrl: "pages/restaurant-details.html",
controller: "RestaurantDetailsController"
})
.when("/hotel", {
templateUrl: "pages/hotel.html",
controller: "HotelController"
})
.when("/hotel/:hotelId", {
templateUrl: "pages/hotel-details.html",
controller: "HotelDetailsController"
})
.when("/booking", {
templateUrl: "pages/booking.html",
controller: "BookingController"
})
.when("/booking/:bookingId", {
templateUrl: "pages/booking-details.html",
controller: "BookingDetailsController"
})
.when("/chat", {
templateUrl: "pages/chat.html",
controller: "ChatController"
})
.when("/profile", {
templateUrl: "pages/profile.html",
controller: "ProfileController"
})
.when("/settings", {
templateUrl: "pages/settings.html",
controller: "SettingsController"
})
.otherwise({
redirectTo: "/"
});
});

Step 2: Create the Home Page


1. Create a new folder named pages in the same directory as index.html.
2. Inside the pages folder, create a new HTML file named home.html. This will be the
template for the Home page.
html
<h1>Welcome to the Restaurant and Hotel Booking App</h1>
<p>Discover the best restaurants and book hotels for your next trip!</p>
<a href="#/restaurants">View Restaurants</a>
<a href="#/hotel">Book a Hotel</a>

3. Create a new JavaScript file named homeController.js in the same directory as


index.html. This will be the controller for the Home page.
javascript
app.controller("HomeController", function($scope) {
// Controller logic for the Home page
});

Step 3: Create the Restaurants Page


1. Inside the pages folder, create a new HTML file named restaurants.html. This will
be the template for the Restaurants page.
html
<h1>Explore Restaurants</h1>
<!-- Display a list of restaurants -->
<ul>
<li ng-repeat="restaurant in restaurants">
<a href="#/restaurants/{{ restaurant.id }}">{{ restaurant.name }}</a>
</li>
</ul>
<a href="#/chat">Open Chat Room</a>
2. Create a new JavaScript file named restaurantsController.js in the same
directory as index.html. This will be the controller for the Restaurants page.

javascript
app.controller("RestaurantsController", function($scope) {
$scope.restaurants = [
{ id: 1, name: "Restaurant 1" },
{ id: 2, name: "Restaurant 2" },
{ id: 3, name: "Restaurant 3" }
];
});

Step 4: Create the Restaurant Details Page


1. Inside the pages folder, create a new HTML file named restaurant-details.html.
This will be the template for the Restaurant Details page.
html
<h1>Restaurant Details</h1>
<!-- Display the details of the selected restaurant -->
<p>{{ restaurantDetails.name }}</p>
<p>{{ restaurantDetails.description }}</p>

2. Create a new JavaScript file named restaurantDetailsController.js in thesame


directory as index.html. This will be the controller for the Restaurant Details page.

javascript
app.controller("RestaurantDetailsController", function($scope, $routeParams) {
// Get the restaurant ID from the route parameters
var restaurantId = $routeParams.restaurantId;

// Define the details of the selected restaurant based on the ID


if (restaurantId === "1") {
$scope.restaurantDetails = {
name: "Restaurant 1",
description: "This is the description for Restaurant 1."
};
} else if (restaurantId === "2") {
$scope.restaurantDetails = {
name: "Restaurant 2",
description: "This is the description for Restaurant 2."
};
} else if (restaurantId === "3") {
$scope.restaurantDetails = {
name: "Restaurant 3",
description: "This is the description for Restaurant 3."
};
}
});

Step 5: Create the Hotel Page


1. Inside the pages folder, create a new HTML file named hotel.html. This will be the
template for the Hotel page.
html
<h1>Book a Hotel</h1>
<!-- Display a search form to find hotels -->
<form>
<label for="location">Location:</label>
<input type="text" id="location" ng-model="hotelSearch.location">
<label for="check-in">Check-In Date:</label>
<input type="date" id="check-in" ng-model="hotelSearch.checkIn">
<label for="check-out">Check-Out Date:</label>
<input type="date" id="check-out" ng-model="hotelSearch.checkOut">
<button type="button" ng-click="searchHotels()">Search</button>
</form>

2. Create a new JavaScript file named hotelController.js in the same directory as


index.html. This will be the controller for the Hotel page.

javascript
app.controller("HotelController", function($scope) {
$scope.hotelSearch = {
location: "",
checkIn: "",
checkOut: ""
};

$scope.searchHotels = function() {
// Implement logic to search for hotels based on the search criteria
console.log("Searching for hotels...");
};
});

Step 6: Create the Hotel Details Page


Follow the same steps as above to create the Hotel Details page (hotel-details.html) and its
corresponding controller (hotelDetailsController.js).

Step 7: Create the Booking Page


Follow the same steps as above to create the Booking page (booking.html) and its
corresponding controller (bookingController.js).

Step 8: Create the Booking Details Page


Follow the same steps as above to create the Booking Details page (booking-details.html)
and its corresponding controller (bookingDetailsController.js).

Step 9: Create the Chat Room Page


Follow the same steps as above to create the Chat Room page (chat.html) and its corresponding
controller (chatController.js).

Step 10: Create the Profile Page


Follow the same steps as above to create the Profile page (profile.html) and its corresponding
controller (profileController.js).

Step 11: Create the Settings Page


Follow the same steps as above to create the Settings page (settings.html) and its
corresponding controller (settingsController.js).

You might also like