Angular Js Chapter
Angular Js Chapter
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.
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>
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">
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.
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.
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."
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 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.
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
JavaScript:
<script>
var app = angular.module('myApp', []);
app.service('userService', function($http) {
this.getUser = function(userId) {
return $http.get('/api/users/' + userId);
};
});
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.
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
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.
JavaScript:
<script>
var app = angular.module('todoApp', []);
$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 }}.
JavaScript:
<script>
var app = angular.module('weatherApp', []);
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'
}
};
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 }}.
JavaScript:
<script>
var app = angular.module('imageGalleryApp', []);
$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.
$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.
JavaScript:
<script>
var app = angular.module('authApp', []);
$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
};
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
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 = "";
submitButton.addEventListener("click", nextQuestion);
}
function checkAnswer(event) {
var selectedChoice = event.target.textContent;
function nextQuestion() {
currentQuestion++;
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.
2. JavaScript:
var isLoggedIn = false;
document.getElementById("login-form").addEventListener("submit", function(event)
{
event.preventDefault();
login(username, password);
});
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
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.
mkdir my-angularjs-project
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:
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:
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
});
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.
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.
$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=["*"],
)
@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', []);
$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.
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: "/"
});
});
javascript
app.controller("HomeController", function($scope) {
// Controller logic for the Home page
});
javascript
app.controller("ProductsController", function($scope) {
$scope.products = [
{ name: "Product 1", price: 10 },
{ name: "Product 2", price: 20 },
{ name: "Product 3", price: 30 }
];
});
javascript
app.controller("CartController", function($scope) {
// Controller logic for the Cart page
});
javascript
app.controller("CheckoutController", function($scope) {
// Controller logic for the Checkout page
});
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: "/"
});
});
javascript
app.controller("HomeController", function($scope) {
// Controller logic for the Home page
});
javascript
app.controller("CoursesController", function($scope) {
$scope.courses = [
{ id: 1, name: "Course 1" },
{ id: 2, name: "Course 2" },
{ id: 3, name: "Course 3" }
];
});
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);
});
});
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 = "";
};
});
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"
};
});
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: "/"
});
});
javascript
app.controller("RestaurantsController", function($scope) {
$scope.restaurants = [
{ id: 1, name: "Restaurant 1" },
{ id: 2, name: "Restaurant 2" },
{ id: 3, name: "Restaurant 3" }
];
});
javascript
app.controller("RestaurantDetailsController", function($scope, $routeParams) {
// Get the restaurant ID from the route parameters
var restaurantId = $routeParams.restaurantId;
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...");
};
});