[go: up one dir, main page]

0% found this document useful (0 votes)
89 views45 pages

UNIT-IV-Express-Angular

This document provides a comprehensive guide to getting started with Express.js, a web framework for Node.js. It covers the installation process, creating a basic application, configuring routes, using middleware, handling requests and responses, and error handling. Additionally, it explains how to utilize request and response objects effectively, including accessing parameters, headers, and setting status codes.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
89 views45 pages

UNIT-IV-Express-Angular

This document provides a comprehensive guide to getting started with Express.js, a web framework for Node.js. It covers the installation process, creating a basic application, configuring routes, using middleware, handling requests and responses, and error handling. Additionally, it explains how to utilize request and response objects effectively, including accessing parameters, headers, and setting status codes.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 45

UNIT-IV

EXPRESS AND ANGULAR


EXPRESS.JS
GETTING STARTED WITH EXPRESS
Getting started with Express.js is pretty straightforward! Express is a fast, minimalist web
framework for Node.js that helps you build web applications and APIs. Here's how you can get
started:
1. Set up Node.js and npm
First, make sure you have Node.js installed. If you don't have it installed, you can download it
from here. npm (Node Package Manager) is bundled with Node.js, and you'll use it to install
Express.
Check if you already have them installed:
node -v
npm -v
2. Initialize a new Node.js project
Create a new directory for your project and initialize a new Node.js project:
mkdir my-express-app
cd my-express-app
npm init -y
This will create a package.json file with default values.
3. Install Express
Now, you can install Express using npm:
npm install express
This will add Express as a dependency in your project.
4. Create a basic Express app
Create a new file named app.js (or index.js if you prefer):
touch app.js
Now, open app.js and set up a basic Express server:
// Import Express module
const express = require('express');

// Create an Express app


const app = express();

// Define a route for the homepage


app.get('/', (req, res) => {
res.send('Hello, world!');
});

1
// Start the server on port 3000
app.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});
5. Run your app
Now, start the server by running:
node app.js
You should see:
Server is running on http://localhost:3000
Go to http://localhost:3000 in your browser, and you should see "Hello, world!".
6. Adding more routes
You can easily add more routes to your application. For example:
app.get('/about', (req, res) => {
res.send('This is the about page');
});

app.get('/contact', (req, res) => {


res.send('This is the contact page');
});
7. Using Middleware
Express allows you to use middleware to handle requests. For example, you can use built-in
middleware like express.json() to parse JSON request bodies:
app.use(express.json());

app.post('/data', (req, res) => {


console.log(req.body); // Access JSON data sent in the request
res.send('Data received');
});
8. Handling Static Files
You can serve static files (like images, CSS, or JavaScript files) using Express’s express.static
middleware. Just add this line to your app:
app.use(express.static('public'));
Make sure you have a public folder in your project directory.

CONFIGURING ROUTES

2
In Express.js, routes define how an application responds to client requests for specific
endpoints. Configuring routes in Express.js involves creating route handlers for specific HTTP
methods (GET, POST, PUT, DELETE, etc.) at specific URL paths.
Basic Route Configuration
1. Setting up Express: First, you need to install Express and set up a basic application:
2. npm install express
3. Create your Express server (app.js):
4. const express = require('express');
5. const app = express();
6. const port = 3000;
7.
8. // Example route: Handle GET requests to "/"
9. app.get('/', (req, res) => {
10. res.send('Hello, World!');
11. });
12.
13. app.listen(port, () => {
14. console.log(`Server running at http://localhost:${port}`);
15. });
Defining Routes for Different HTTP Methods
1. GET Route: The GET method is used to retrieve data.
2. app.get('/user', (req, res) => {
3. res.send('Getting user data');
4. });
5. POST Route: The POST method is used to send data to the server.
6. app.post('/user', (req, res) => {
7. res.send('Creating user data');
8. });
9. PUT Route: The PUT method is used to update data on the server.
10. app.put('/user/:id', (req, res) => {
11. const userId = req.params.id;
12. res.send(`Updating user with ID ${userId}`);
13. });
14. DELETE Route: The DELETE method is used to delete data from the server.
15. app.delete('/user/:id', (req, res) => {
16. const userId = req.params.id;
17. res.send(`Deleting user with ID ${userId}`);
18. });

3
Route Parameters and Query Strings
 Route Parameters: You can capture values from the URL using route parameters. For
example, /user/:id will capture the id parameter.
 app.get('/user/:id', (req, res) => {
 const userId = req.params.id;
 res.send(`User ID: ${userId}`);
 });
 Query Strings: You can also retrieve query strings using req.query.
 app.get('/search', (req, res) => {
 const query = req.query.q;
 res.send(`Search query: ${query}`);
 });
Middleware for Routes
You can use middleware functions to process requests before they reach your route handlers.
1. Global Middleware (applies to all routes):
2. app.use((req, res, next) => {
3. console.log('Request received');
4. next();
5. });
6. Middleware for specific routes:
7. app.get('/user', (req, res, next) => {
8. console.log('User route accessed');
9. next();
10. }, (req, res) => {
11. res.send('User data');
12. });
Route Handling with Separate Files (Modular Routes)
You can organize your routes into separate files to keep the application structure clean.
1. Create a route file (routes/user.js):
2. const express = require('express');
3. const router = express.Router();
4.
5. // Handle GET requests to /user
6. router.get('/', (req, res) => {
7. res.send('Getting user data');
8. });
9.
10. // Handle POST requests to /user

4
11. router.post('/', (req, res) => {
12. res.send('Creating user data');
13. });
14.
15. module.exports = router;
16. Use the route file in the main app (app.js):
17. const express = require('express');
18. const app = express();
19. const userRoutes = require('./routes/user'); // Import user routes
20.
21. app.use('/user', userRoutes); // Attach user routes to "/user" path
22.
23. const port = 3000;
24. app.listen(port, () => {
25. console.log(`Server running at http://localhost:${port}`);
26. });
Error Handling
You can add error-handling middleware in Express.js as well.
// Error handling middleware
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something broke!');
});
Summary of Common Methods
 app.get(path, callback): Handles GET requests.
 app.post(path, callback): Handles POST requests.
 app.put(path, callback): Handles PUT requests.
 app.delete(path, callback): Handles DELETE requests.
 app.use(path, callback): Used for middleware or routing at specific paths.

USING REQUEST OBJECTS


In Express.js, the req (request) object provides information about the HTTP request made by the
client. It contains details such as the HTTP method, URL, headers, body data, query parameters,
and route parameters.
Here are some key properties and methods you can use with the req object:
1. req.params – Route Parameters
Route parameters are dynamic values in the URL that are captured by Express. These are
defined in the route path with a colon (:), and you can access them through req.params.

5
Example:
app.get('/user/:id', (req, res) => {
const userId = req.params.id; // Capture the user ID from the URL
res.send(`User ID is ${userId}`);
});
If the URL is /user/123, req.params.id will return 123.
2. req.query – Query Parameters
Query parameters are appended to the URL after a question mark (?) and are typically used for
filtering, sorting, or pagination. You can access query parameters using req.query.
Example:
app.get('/search', (req, res) => {
const searchTerm = req.query.q; // Capture query parameter 'q'
res.send(`Search term is: ${searchTerm}`);
});
If the URL is /search?q=node, req.query.q will return node.
3. req.body – Request Body
When sending data in POST or PUT requests (often in JSON or form format), the request body is
where the data is stored. Express provides middleware like express.json() to parse the incoming
request body.
To use req.body, you need to configure middleware that parses the body (like express.json() for
JSON or express.urlencoded() for form data).
Example:
app.use(express.json()); // Parse incoming JSON data

app.post('/user', (req, res) => {


const user = req.body; // Capture the data sent in the request body
res.send(`User data received: ${JSON.stringify(user)}`);
});
If the request body is { "name": "John", "age": 30 }, req.body will contain that data.
4. req.headers – Request Headers
The headers contain metadata about the request, such as the content type, authorization
tokens, etc. You can access request headers via req.headers.
Example:
app.get('/check', (req, res) => {
const userAgent = req.headers['user-agent']; // Capture the User-Agent header
res.send(`Your User-Agent is: ${userAgent}`);
});

6
If the request includes a header like User-Agent: Mozilla/5.0, req.headers['user-agent'] will
return "Mozilla/5.0".
5. req.method – HTTP Method
The req.method property returns the HTTP method (GET, POST, etc.) used for the request.
Example:
app.all('*', (req, res) => {
res.send(`You made a ${req.method} request`);
});
If the request is a GET request, req.method will return "GET".
6. req.url – Request URL
The req.url property contains the full URL of the request, including the query string but
excluding the domain name.
Example:
app.get('*', (req, res) => {
res.send(`The requested URL is: ${req.url}`);
});
If the URL is /search?q=express, req.url will be /search?q=express.
7. req.cookies – Cookies (requires cookie-parser middleware)
Express doesn't handle cookies by default, but you can use the cookie-parser middleware to
parse cookies from incoming requests.
First, install cookie-parser:
npm install cookie-parser
Then use it in your application:
const cookieParser = require('cookie-parser');
app.use(cookieParser());

app.get('/cookie', (req, res) => {


const userCookie = req.cookies.user; // Access a specific cookie
res.send(`User cookie value: ${userCookie}`);
});
If the request contains a cookie user=John, req.cookies.user will return "John".
8. req.ip – Client IP Address
You can retrieve the IP address of the client making the request using req.ip.
Example:
app.get('/client-ip', (req, res) => {
const clientIp = req.ip;
res.send(`Your IP address is: ${clientIp}`);
});

7
9. req.hostname – Request Hostname
The req.hostname property contains the hostname (domain) of the request.
Example:
app.get('/host', (req, res) => {
const host = req.hostname;
res.send(`Your hostname is: ${host}`);
});
10. req.protocol – Protocol
The req.protocol property contains the protocol used (either "http" or "https").
Example:
app.get('/protocol', (req, res) => {
const protocol = req.protocol;
res.send(`The protocol used is: ${protocol}`);
});
Example Combining Multiple Properties:
app.post('/submit', (req, res) => {
const userId = req.params.id; // Capture route parameter
const searchTerm = req.query.q; // Capture query string parameter
const userData = req.body; // Capture data in the request body
const userAgent = req.headers['user-agent']; // Capture headers

res.send(`
User ID: ${userId}
Search Term: ${searchTerm}
User Data: ${JSON.stringify(userData)}
User-Agent: ${userAgent}
`);
});

These are some of the most commonly used req object properties. They allow you to interact
with the data and metadata sent by the client in an HTTP request.

USING RESPONSE OBJECTS


In Express.js, the res (response) object is used to send a response back to the client. It contains
methods to set HTTP status codes, send data, and manage the response headers. Here's a
breakdown of how to use the res object effectively.
1. Sending Data in the Response
You can send a variety of data types in the response, such as strings, JSON objects, and HTML.

8
 Sending Text/HTML: You can send plain text or HTML content using res.send().
 app.get('/text', (req, res) => {
 res.send('Hello, world!');
 });

 app.get('/html', (req, res) => {
 res.send('<h1>Welcome to Express!</h1>');
 });
 Sending JSON: You can send JSON data using res.json(). Express will automatically set
the correct Content-Type header (application/json).
 app.get('/json', (req, res) => {
 res.json({ message: 'Hello, JSON!' });
 });
 Sending a Buffer: You can also send binary data like an image or file buffer using
res.send().
 app.get('/image', (req, res) => {
 const imageBuffer = fs.readFileSync('path/to/image.jpg');
 res.send(imageBuffer);
 });
2. Setting HTTP Status Codes
The res object allows you to set the HTTP status code for the response. By default, Express
sends a status code of 200 for a successful request. You can change this with res.status(code).
 Setting the Status Code:
 app.get('/notfound', (req, res) => {
 res.status(404).send('Page not found!');
 });
This sets the response status code to 404 (Not Found) and sends a message saying "Page not
found!"
 Common Status Codes:
o 200 OK: Success
o 201 Created: Successfully created a resource (e.g., when POSTing data)
o 400 Bad Request: Invalid request from the client
o 401 Unauthorized: Authentication required
o 404 Not Found: Requested resource not found
o 500 Internal Server Error: Generic error from the server
3. Setting Response Headers
You can modify or set custom response headers with res.set() or res.header().
 Setting a single header:

9
 app.get('/header', (req, res) => {
 res.set('X-Custom-Header', 'HelloWorld');
 res.send('Custom header set!');
 });
 Setting multiple headers:
 app.get('/multiple-headers', (req, res) => {
 res.set({
 'Content-Type': 'application/json',
 'X-Powered-By': 'Express'
 });
 res.send('Multiple headers set');
 });
 Access-Control-Allow-Origin Header: If you're dealing with CORS (Cross-Origin Resource
Sharing), you can set the Access-Control-Allow-Origin header to allow resources to be
shared across domains.
 app.get('/cors', (req, res) => {
 res.set('Access-Control-Allow-Origin', '*');
 res.send('CORS header set!');
 });
4. Redirecting Responses
You can redirect the client to another URL with res.redirect().
 Basic Redirect:
 app.get('/redirect', (req, res) => {
 res.redirect('https://www.example.com');
 });
 Redirect with a Status Code: You can also specify a status code for the redirect (default
is 302 Found).
 app.get('/moved', (req, res) => {
 res.redirect(301, 'https://www.new-url.com'); // 301 Moved Permanently
 });
5. Sending Files
You can send a file to the client with res.sendFile(). This is useful when serving images, PDFs, or
other static files.
 Sending a file:
 app.get('/file', (req, res) => {
 res.sendFile(__dirname + '/file.pdf'); // Path to the file
 });
 Sending a file with custom headers:

10
 app.get('/download', (req, res) => {
 res.download(__dirname + '/file.pdf', 'custom-filename.pdf');
 });
6. Cookie Management
You can set and send cookies using res.cookie(). Cookies are sent as part of the response
headers and can be accessed on subsequent requests.
 Setting a cookie:
 app.get('/setcookie', (req, res) => {
 res.cookie('username', 'JohnDoe');
 res.send('Cookie has been set');
 });
 Setting an encrypted cookie (requires cookie-parser middleware):
 app.use(cookieParser('secret-key')); // Secret key for encryption

 app.get('/setsecurecookie', (req, res) => {
 res.cookie('username', 'JohnDoe', { signed: true });
 res.send('Secure cookie has been set');
 });
 Accessing cookies:
 app.get('/getcookie', (req, res) => {
 const username = req.cookies.username; // Access unencrypted cookies
 const signedUsername = req.signedCookies.username; // Access signed cookies
 res.send(`Username cookie: ${username}, Signed Username: ${signedUsername}`);
 });
7. Ending the Response (Calling res.end())
If you want to manually end the response without sending any data, you can call res.end().
 Ending a response:
 app.get('/end', (req, res) => {
 res.end('Response ended');
 });
This method is not commonly needed as res.send() and other methods will end the response
automatically.
8. Handling Asynchronous Responses
If you have asynchronous tasks (e.g., fetching data from a database), you can use async/await or
callbacks to handle responses.
 Using async/await with a database query:
 app.get('/user', async (req, res) => {
 try {

11
 const user = await getUserFromDatabase(); // Assume this is an async function
 res.json(user);
 } catch (error) {
 res.status(500).send('Server error');
 }
 });
Example Combining Multiple Response Methods:
app.get('/response-example', (req, res) => {
// Setting status code and headers
res.status(200).set('X-Custom-Header', 'MyCustomHeader');

// Sending JSON data


res.json({ message: 'This is a JSON response', success: true });

// Redirecting
res.redirect('https://www.new-site.com');
});
Summary of Common Methods
 res.send(): Sends data to the client (text, JSON, HTML, etc.).
 res.status(code): Sets the HTTP status code.
 res.json(): Sends a JSON response.
 res.redirect(url): Redirects to another URL.
 res.sendFile(path): Sends a file to the client.
 res.cookie(name, value): Sets a cookie.
 res.set(): Sets custom response headers.
 res.download(): Allows downloading a file.
 res.end(): Ends the response without sending data (rarely needed).
With these methods, you can control how your application responds to HTTP requests, manage
data and files, and handle cookies, headers, and redirection.

12
ANGULAR.JS
IMPORTANCE OF ANGULAR
AngularJS, the JavaScript framework developed by Google, was one of the first frameworks to
bring structure and maintainability to client-side web applications. Although it has been
succeeded by Angular (2+), AngularJS still played an important role in web development and
had a significant impact on how modern web frameworks were developed.
Here are some of the key reasons why AngularJS was important:
1. Two-Way Data Binding
 Description: AngularJS introduced the concept of two-way data binding, which means
that changes in the UI are automatically reflected in the application’s data model, and
changes to the model are reflected in the UI.
 Importance: This feature minimized the need for manual DOM manipulation, allowing
developers to focus more on the application logic rather than manually updating the
view.
2. Declarative UI with Directives
 Description: AngularJS uses directives to create custom HTML elements and attributes
that control DOM behavior, making it easier to create reusable components.
 Importance: This declarative approach meant that developers could focus more on
describing the behavior of the UI rather than imperatively defining it, which led to more
maintainable and readable code.
3. MVC (Model-View-Controller) Architecture
 Description: AngularJS encourages the use of the MVC architecture, where the
application is divided into three parts: the Model (data), the View (UI), and the
Controller (logic).
 Importance: This separation of concerns helped organize code into clear layers, making
it easier to develop and maintain large-scale applications.
4. Dependency Injection (DI)

13
 Description: AngularJS has a built-in dependency injection system that allows
components (services, controllers, etc.) to receive the dependencies they need rather
than hardcoding them.
 Importance: DI promotes loose coupling, easier testing, and a cleaner design, allowing
for more maintainable code. It also made unit testing and mocking of components much
easier.
5. Single Page Application (SPA) Support
 Description: AngularJS enabled the creation of Single Page Applications (SPAs) where
the page is loaded once, and the content is dynamically updated using AJAX.
 Importance: SPAs significantly improve user experience by making web apps feel faster
and more like native applications. AngularJS's routing and state management features
helped achieve this.
6. Reusable Components
 Description: AngularJS introduced the concept of components (although in a less
advanced form than in Angular 2+), which allowed developers to build modular, reusable
parts of an application (like custom form elements, widgets, etc.).
 Importance: Reusable components helped in building maintainable, scalable, and
testable applications, which was especially useful in large teams and long-term projects.
7. Testing Support
 Description: AngularJS was designed with testing in mind. It provided tools to easily unit
test controllers, services, and other parts of the application. It also integrated well with
testing frameworks like Jasmine and Karma.
 Importance: AngularJS's emphasis on testability allowed developers to build more
reliable and bug-free applications, ensuring that tests could be automated and
integrated into the development process.
8. End-to-End Tooling
 Description: AngularJS came with built-in tooling and support for building, testing, and
deploying applications. Tools like Angular CLI (for later versions) and ngMock (for unit
testing) helped streamline development.
 Importance: With a strong development ecosystem, AngularJS made it easier for
developers to set up projects, manage builds, and ensure the applications followed best
practices.
9. Community and Ecosystem
 Description: AngularJS had a large, active community and strong backing from Google,
which ensured continuous updates, tutorials, and third-party libraries for extending
AngularJS applications.

14
 Importance: The large ecosystem made it easy for developers to find support, resources,
and tools to improve productivity, and it facilitated innovation in the web development
community.
10. Cross-Platform Support
 Description: While AngularJS was primarily for web applications, it paved the way for
cross-platform development by enabling integration with mobile frameworks like Ionic,
which allowed developers to build mobile apps using AngularJS.
 Importance: AngularJS helped developers extend the reach of their applications beyond
the web to mobile platforms, leading to the creation of hybrid mobile apps.
11. Comprehensive Documentation
 Description: AngularJS came with excellent official documentation that helped both
beginners and advanced developers understand the framework's concepts and
practices.
 Importance: Clear, comprehensive documentation made learning and adopting
AngularJS much easier, which contributed to its widespread adoption in the web
development community.
Conclusion:
AngularJS was groundbreaking in many ways and laid the foundation for modern front-end
development frameworks. It was instrumental in advancing the concept of client-side JavaScript
frameworks and revolutionized how developers approached building dynamic, complex, and
interactive web applications. Despite its successor (Angular 2+) being more powerful and
efficient, AngularJS remains a key milestone in the evolution of web development. It gave rise to
many concepts and tools that are now standard in frameworks today.

UNDERSTANDING ANGULAR
Understanding AngularJS
AngularJS is an open-source JavaScript framework developed by Google to help developers
build dynamic, single-page web applications (SPAs). AngularJS simplifies the development and
testing of client-side applications by providing a structured approach and tools for building
applications efficiently.
At its core, AngularJS helps separate the application's concerns (data, UI, and behavior),
allowing for maintainable, reusable, and testable code.
Key Concepts in AngularJS
1. Two-Way Data Binding:
o AngularJS automatically synchronizes data between the model (JavaScript
objects) and the view (HTML). This means when the model changes, the view is
updated automatically, and vice versa.
o Example:

15
o <div ng-app="app">
o <input type="text" ng-model="name">
o <p>Hello, {{ name }}</p>
o </div>
Here, the ng-model directive binds the input field to the model name. Any changes in the
input field will automatically update the name in the paragraph.
2. Directives:
o Directives are special markers in the DOM (HTML) that tell AngularJS to add
behavior to a DOM element. They extend HTML with custom attributes or
elements, such as ng-model, ng-bind, ng-repeat, and ng-if.
o Common Directives:
 ng-model: Binds an HTML element to the model.
 ng-repeat: Loops through an array and displays it in the view.
 ng-if: Conditionally includes or removes elements from the DOM.
 ng-click: Attaches click event handlers to elements.
3. MVC (Model-View-Controller) Architecture:
o AngularJS encourages the Model-View-Controller architecture, which separates
the application into three main parts:
 Model: Represents the data and business logic of the application.
 View: The user interface that displays the data (HTML).
 Controller: The logic that connects the Model and the View, handling
user input and updating the Model or View accordingly.
This structure helps organize the application code, making it easier to manage and scale.
4. Dependency Injection (DI):
o Dependency Injection is a technique that allows components (such as
controllers and services) to receive their dependencies (like services, factories,
or other objects) from an external source rather than creating them internally.
o Importance: DI promotes loose coupling and improves code maintainability by
making it easier to swap out or mock dependencies for testing.
o Example:
o angular.module('app', [])
o .controller('MyController', function($scope, $http) {
o // Using $http service to fetch data
o $http.get('api/data').then(function(response) {
o $scope.data = response.data;
o });
o });
5. Services:

16
o Services are JavaScript objects that handle business logic and data interaction.
They can be reused throughout the application, making the code modular and
easier to maintain.
o Services in AngularJS are singletons, meaning that once a service is created, it
can be injected into multiple components, like controllers, directives, or other
services.
6. Filters:
o Filters are used to format data before displaying it in the view. They can be
applied to variables inside expressions, in the ng-repeat directive, or even
inside controllers.
o Common Filters:
 currency: Formats a number as a currency value.
 date: Formats a date according to a specified pattern.
 uppercase / lowercase: Converts a string to uppercase or lowercase.
Example:
<div>{{ price | currency }}</div>
7. Routing:
o Routing in AngularJS allows you to create single-page applications by loading
different views or templates without reloading the entire page. This is achieved
using the ngRoute module.
o Example:
o angular.module('app', ['ngRoute'])
o .config(function($routeProvider) {
o $routeProvider
o .when('/home', {
o templateUrl: 'home.html',
o controller: 'HomeController'
o })
o .when('/about', {
o templateUrl: 'about.html',
o controller: 'AboutController'
o });
o });
8. Controllers:
o Controllers are JavaScript functions that are responsible for handling the logic
of an application. They connect the Model (data) with the View (UI) and can
manipulate data based on user input.
o Example:

17
o angular.module('app', [])
o .controller('MyController', function($scope) {
o $scope.message = 'Hello, AngularJS!';
o });
9. Templates:
o A template in AngularJS is a combination of HTML and Angular-specific markup
(directives and expressions) that defines the structure of the user interface.
o Templates are dynamic and update automatically when the model changes due
to Angular's two-way data binding.
10. Modules:
o A module is a container for various parts of an AngularJS application like
controllers, services, directives, and filters. It helps organize the code into
reusable and logical components.
o Example:
o angular.module('app', [])
o .controller('MyController', function($scope) {
o // Controller code
o });
The Flow of AngularJS Application
1. Bootstrap: The AngularJS application begins with the ng-app directive, which initializes
the AngularJS framework and the root module.
2. Dependency Injection: AngularJS injects the necessary services and components into
the application based on the dependency definitions.
3. Views and Templates: The view is rendered dynamically using templates. Directives
control how the view behaves, such as binding data or reacting to events.
4. Two-Way Data Binding: Any change to the model (data) is reflected in the view and
vice versa, ensuring that the UI is always in sync with the model.
5. Controllers: The controller manages the data and logic, updating the model when
necessary and manipulating the view based on user input.
Advantages of AngularJS
1. Simplified Development: With features like two-way data binding, MVC architecture,
and dependency injection, AngularJS helps developers build applications quickly and
efficiently.
2. Reusability: Components like directives, services, and controllers are reusable across
the application, promoting modularity.
3. Testability: AngularJS encourages a test-driven approach by making it easy to test
controllers, services, and components.

18
4. Cross-Platform: AngularJS can be used to build both web and mobile applications using
frameworks like Ionic.
Conclusion
AngularJS revolutionized the way developers build web applications by providing a structured
framework for creating dynamic, single-page applications. With its key features like two-way
data binding, directives, dependency injection, and testing tools, AngularJS simplified the
development of complex, interactive web applications. Although it has been superseded by
Angular (2+), AngularJS remains a significant milestone in the evolution of modern web
frameworks.

CREATING A BASIC ANGULAR APPLICATION


To create a basic AngularJS application, follow these simple steps. I'll guide you through the
process of setting up a simple AngularJS app, where we will display dynamic data and use
AngularJS's core features like controllers and two-way data binding.
Step 1: Set Up the HTML File
1. Create an HTML file: This will contain your AngularJS application, including the
directives and logic.
2. Include AngularJS: You can either download AngularJS and link it locally, or use a CDN
to load AngularJS.
Step 2: Basic HTML and AngularJS Setup
Let's create a simple AngularJS app that binds a variable to the view and updates the view
based on user input.
Example:
<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Basic AngularJS Application</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></
script>
</head>
<body>

<div ng-controller="myController">
<h1>Hello, {{ name }}!</h1>
<input type="text" ng-model="name" placeholder="Enter your name">
</div>

19
<script>
// Creating an AngularJS module
var app = angular.module('myApp', []);

// Creating a controller for the application


app.controller('myController', function($scope) {
$scope.name = "AngularJS User"; // Initial value
});
</script>

</body>
</html>
Explanation:
1. ng-app="myApp": The ng-app directive is used to define the AngularJS application.
Here, we name the app myApp.
2. ng-controller="myController": The ng-controller directive defines the controller for the
HTML element. It links the view with the controller logic.
3. ng-model="name": The ng-model directive creates a two-way data binding between
the input field and the name variable in the controller. Whatever is typed into the
input field will automatically update the name variable, and the name will
automatically be reflected in the <h1> tag.
4. $scope.name: In the controller, $scope is used to define variables that will be available
to the view. We initialize the name variable with the value "AngularJS User", which is
displayed until the user types something else into the input field.
5. AngularJS CDN: We are using a CDN to load the AngularJS library. This is the simplest
way to include AngularJS in your project without having to download and store the
library locally.
Step 3: Open the HTML File
1. Save the file as index.html (or any name with .html extension).
2. Open the file in any modern web browser (Chrome, Firefox, Edge, etc.).
3. You should see a heading that says Hello, AngularJS User! and an input field. When
you type in the input field, the text in the heading should update automatically.
Step 4: Optional Features and Enhancements
You can enhance this basic app further by adding more AngularJS features, such as:
1. Using more directives:
o ng-repeat for loops
o ng-show / ng-hide for conditionally displaying content

20
2. Adding more controllers: You can have multiple controllers for different parts of the
page.
3. Creating custom services and filters: These allow you to organize logic and enhance
functionality.
Example: Using ng-repeat to Display a List
<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Basic AngularJS Application</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></
script>
</head>
<body>

<div ng-controller="myController">
<h1>Hello, {{ name }}!</h1>
<input type="text" ng-model="name" placeholder="Enter your name">

<h2>List of Items</h2>
<ul>
<li ng-repeat="item in items">{{ item }}</li>
</ul>
</div>

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

app.controller('myController', function($scope) {
$scope.name = "AngularJS User"; // Initial value
$scope.items = ["Apple", "Banana", "Orange", "Grapes"]; // List of items
});
</script>

</body>
</html>
In this enhanced version:

21
 We added an ng-repeat directive to loop through an array items and display each item
as a list in the view.
Step 5: Test Your Application
 As you type your name in the input box, the value in the heading (<h1>) will update
automatically.
 You’ll also see a dynamic list of fruits below the input.
Conclusion:
You've now created a basic AngularJS application! This simple example shows how to use
AngularJS directives like ng-app, ng-model, and ng-controller to build a dynamic web page.
From here, you can further expand your app by adding more functionality such as services,
routing, and more interactive features.
Although AngularJS has been largely replaced by Angular (2+), understanding AngularJS is still
a good way to learn the foundational concepts that are part of modern frameworks.

ANGULAR COMPONENTS
AngularJS Components
In AngularJS (version 1.x), components were introduced to provide a more structured way to
organize code, making it easier to reuse and maintain. Components in AngularJS are essentially
directives with a simplified and more consistent API. They encapsulate the logic and the view,
making it easier to manage complex user interfaces.
Why Use Components in AngularJS?
 Encapsulation: Components encapsulate both the template (HTML) and the controller
(logic) in one cohesive unit.
 Reusability: Components can be reused across different parts of the application, leading
to modular code.
 Maintainability: By using components, it’s easier to manage, test, and extend your
application.
Structure of an AngularJS Component
A component in AngularJS typically consists of:
1. Template: The HTML markup that defines the structure of the view.
2. Controller: The JavaScript logic that defines the behavior of the component.
3. Bindings: The mechanism for passing data between the component and its parent scope
or other components.
Basic Syntax for Creating a Component in AngularJS
Components in AngularJS are created using the angular.module().component() method. The
component definition includes:
 template: The HTML template or an inline string of HTML.
 controller: The controller function or object associated with the component.

22
 bindings: Data binding between the parent and the component.
Example 1: Basic Component in AngularJS
<!DOCTYPE html>
<html lang="en" ng-app="app">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AngularJS Component Example</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body>

<div ng-controller="MainController">
<greeting name="John"></greeting>
</div>

<script>
angular.module('app', [])
.component('greeting', {
template: '<h1>Hello, {{$ctrl.name}}!</h1>',
controller: function() {
// You can add logic here if needed
},
bindings: {
name: '@'
}
})
.controller('MainController', function($scope) {
// You can define scope data if needed
});
</script>

</body>
</html>
Explanation:
1. ng-app="app": This initializes the AngularJS app.
2. ng-controller="MainController": A controller for the main scope that can be used to
manage the application logic.

23
3. : The component greeting is used here. It accepts a name attribute which is bound to the
controller.
4. Component Definition:
o template: This is where you define the HTML structure.
o controller: The function that manages the logic of the component.
o bindings: The name is bound from the parent scope to the component using the
@ symbol for one-way binding (string).
5. Bindings: The name attribute passed from the parent scope is passed into the
component. The value of name is displayed in the h1 tag.
Example 2: Component with Input Binding
This example demonstrates a component with input and output bindings, which allows
interaction with the parent scope.
<!DOCTYPE html>
<html lang="en" ng-app="app">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AngularJS Component with Input Binding</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body>

<div ng-controller="MainController">
<greeting name="John" on-greeting="showAlert(name)"></greeting>
</div>

<script>
angular.module('app', [])
.component('greeting', {
template: `
<h1>Hello, {{$ctrl.name}}!</h1>
<button ng-click="$ctrl.greet()">Greet</button>
`,
controller: function() {
var ctrl = this;

// Greet method that triggers the event passed from parent


ctrl.greet = function() {

24
ctrl.onGreeting({name: ctrl.name});
};
},
bindings: {
name: '@', // Input binding (one-way from parent to child)
onGreeting: '&' // Output binding (event callback to parent)
}
})
.controller('MainController', function($scope) {
// A function that will be triggered by the component
$scope.showAlert = function(name) {
alert('Hello, ' + name);
};
});
</script>

</body>
</html>
Explanation:
1. Input Binding: The name is passed from the parent scope to the component using the @
binding.
2. Output Binding: The on-greeting attribute in the parent scope passes an event handler
showAlert(name) to the component. When the button is clicked, the component calls
onGreeting({name: ctrl.name}) to trigger the alert in the parent scope.
3. Component Behavior: The greet() method in the component's controller invokes the
parent-defined method showAlert using the & binding, allowing interaction with the
parent scope.
Component Lifecycle Hooks
AngularJS components have lifecycle hooks that can be used to manage component behavior at
different stages. For example:
 $onInit: Called once the component has been initialized.
 $onChanges: Called whenever the component’s bindings change.
 $onDestroy: Called when the component is about to be destroyed.
Example: Using $onInit Hook
angular.module('app', [])
.component('greeting', {
template: '<h1>Hello, {{$ctrl.name}}!</h1>',
controller: function() {

25
this.$onInit = function() {
this.name = 'AngularJS User';
};
}
});
In this example, the $onInit lifecycle hook initializes the name variable when the component is
created.
Conclusion
AngularJS components are a powerful feature that allows you to encapsulate both logic and UI
in a reusable, modular, and maintainable way. Components improve code organization and help
you build more complex applications with less effort. Even though AngularJS is now considered
legacy (with Angular 2+ being the modern framework), understanding AngularJS components is
a great way to grasp fundamental concepts in modern JavaScript frameworks.
ANGULAR EXPRESSIONS
AngularJS Expressions
In AngularJS, expressions are used to bind data from the model (JavaScript variables or
functions) to the view (HTML). They are similar to JavaScript expressions but are evaluated in
the context of the AngularJS scope, allowing the automatic update of the view when the model
changes (thanks to two-way data binding).
AngularJS expressions can be written within {{ }} curly braces, known as interpolation, or used
with directives like ng-bind.
Key Features of AngularJS Expressions
1. Data Binding: AngularJS expressions automatically update the view when the model
changes, thanks to its two-way data binding.
2. AngularJS Scope: Expressions can access properties and functions defined in the
AngularJS scope (i.e., the controller's $scope object).
3. No Logic: AngularJS expressions are not allowed to contain certain JavaScript logic like
loops, conditionals, or assignments. They are meant for evaluating values and simple
logic (e.g., arithmetic, string concatenation, etc.).
Example Syntax for AngularJS Expressions
<h1>{{ expression }}</h1>
Where expression can be any valid JavaScript expression (like variables, functions, or
mathematical operations).
Types of AngularJS Expressions
1. Binding Variables: You can bind variables from the AngularJS controller to the HTML
view using expressions.
2. <div ng-app="app" ng-controller="MainController">
3. <p>{{ message }}</p>

26
4. </div>
5. angular.module('app', [])
6. .controller('MainController', function($scope) {
7. $scope.message = "Hello, AngularJS!";
8. });
In this example, the variable message in the controller is displayed in the view using the
AngularJS expression {{ message }}.
9. Evaluating Arithmetic Expressions: You can perform basic arithmetic directly inside the
expression.
10. <p>{{ 10 + 5 }}</p>
This will output 15 in the view.
11. Using Functions in Expressions: You can call functions defined in the controller within
the expression.
12. <div ng-app="app" ng-controller="MainController">
13. <p>{{ addNumbers(10, 5) }}</p>
14. </div>
15. angular.module('app', [])
16. .controller('MainController', function($scope) {
17. $scope.addNumbers = function(a, b) {
18. return a + b;
19. };
20. });
The addNumbers function is invoked within the expression, and the result will be shown (which
is 15 in this case).
21. String Interpolation: You can concatenate strings or create dynamic text using
expressions.
22. <div ng-app="app" ng-controller="MainController">
23. <p>{{ 'Hello, ' + userName + '!' }}</p>
24. </div>
25. angular.module('app', [])
26. .controller('MainController', function($scope) {
27. $scope.userName = "John";
28. });
This will output: Hello, John!
29. Conditional Expressions: You can use ternary operators (condition ? value1 : value2)
within expressions.
30. <div ng-app="app" ng-controller="MainController">
31. <p>{{ age >= 18 ? 'Adult' : 'Minor' }}</p>

27
32. </div>
33. angular.module('app', [])
34. .controller('MainController', function($scope) {
35. $scope.age = 20;
36. });
Based on the condition age >= 18, the expression will display either "Adult" or "Minor". Since
age is 20, the output will be Adult.
AngularJS Expressions vs. JavaScript Expressions
 No Logic or Assignments: AngularJS expressions are simple and do not allow
assignments (e.g., x = 10), loops, or if conditions. They are only for evaluating and
displaying data.
 Automatic Scope Evaluation: AngularJS expressions are evaluated in the context of the
scope, allowing automatic updates when the model changes.
 HTML Binding: AngularJS expressions are designed to be used directly in the HTML view,
while JavaScript expressions generally belong in scripts or controllers.
Using Expressions in Directives
AngularJS allows you to use expressions within many of its built-in directives, such as ng-bind,
ng-repeat, ng-show, and ng-hide.
Example 1: ng-bind with Expression
The ng-bind directive binds an expression to an HTML element. This is useful for replacing the
{{ expression }} syntax when you need to avoid issues with HTML escaping.
<div ng-app="app" ng-controller="MainController">
<p ng-bind="message"></p>
</div>

<script>
angular.module('app', [])
.controller('MainController', function($scope) {
$scope.message = "This is an expression bound with ng-bind!";
});
</script>
Example 2: ng-show/ng-hide with Expression
You can use expressions in directives like ng-show or ng-hide to conditionally display or hide
elements.
<div ng-app="app" ng-controller="MainController">
<button ng-click="toggle()">Toggle Message</button>
<p ng-show="isVisible">This message is conditionally displayed!</p>
</div>

28
<script>
angular.module('app', [])
.controller('MainController', function($scope) {
$scope.isVisible = false;

$scope.toggle = function() {
$scope.isVisible = !$scope.isVisible;
};
});
</script>
Here, the <p> element will show or hide based on the value of isVisible, which changes when
the button is clicked.
Expression Filters
AngularJS provides filters that allow you to format expressions in different ways (e.g., currency,
date, uppercase, etc.). You can use them in expressions to transform data before displaying it.
Example 1: Currency Filter
<p>{{ 12345 | currency }}</p>
This will format the number as a currency (e.g., $12,345.00 depending on the locale).
Example 2: Date Filter
<p>{{ today | date:'yyyy-MM-dd' }}</p>
This will display the today date in the format yyyy-MM-dd.
Example 3: Uppercase/Lowercase Filter
<p>{{ message | uppercase }}</p>
If message is "Hello World", this will display "HELLO WORLD".
Conclusion
AngularJS expressions are a key part of data binding, enabling the automatic synchronization of
the model and the view. They allow you to insert dynamic content into your HTML view,
perform simple logic (e.g., arithmetic, string concatenation, conditional statements), and format
data using filters. The ability to use expressions inside directives like ng-bind, ng-repeat, and ng-
show makes AngularJS a powerful tool for building interactive web applications.

ANGULAR DATA BINDING


AngularJS Data Binding
Data binding is one of the most important features of AngularJS. It refers to the automatic
synchronization of data between the model (JavaScript objects) and the view (HTML). In
AngularJS, data binding allows the application to reflect changes made to the data model
automatically in the view, and vice versa, without having to manually manipulate the DOM.

29
There are two types of data binding in AngularJS:
1. One-way Data Binding
2. Two-way Data Binding
Let's explore both types in detail.

1. One-Way Data Binding


One-way data binding means that data flows in only one direction — from the model
(controller) to the view (HTML) or vice versa.
Example of One-Way Data Binding (Model to View)
In one-way data binding, the model (JavaScript) sends data to the view (HTML), but changes
made in the view will not affect the model.
<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AngularJS One-Way Data Binding</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></
script>
</head>
<body>

<div ng-controller="MainController">
<h1>{{ message }}</h1> <!-- One-way data binding -->
</div>

<script>
angular.module('myApp', [])
.controller('MainController', function($scope) {
$scope.message = "Hello, AngularJS!";
});
</script>

</body>
</html>
In this example:
 The model ($scope.message) is linked to the view (HTML <h1>{{ message }}</h1>).

30
 If the $scope.message changes in the controller, it automatically updates the HTML
<h1>.
 However, changes in the view (e.g., the user typing in the <h1> tag) will not affect the
model.
Example of One-Way Data Binding (View to Model)
In one-way binding from view to model, the data flows from the view (HTML) to the model
(JavaScript). AngularJS uses directives like ng-model to enable this.
For example, an input field bound to a model:
<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AngularJS One-Way Binding</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></
script>
</head>
<body>

<div ng-controller="MainController">
<input type="text" ng-model="message"> <!-- One-way binding from View to Model -->
<h1>{{ message }}</h1> <!-- One-way data binding from Model to View -->
</div>

<script>
angular.module('myApp', [])
.controller('MainController', function($scope) {
$scope.message = "Hello, AngularJS!";
});
</script>

</body>
</html>
In this case:
 Changes in the input field automatically update the model ($scope.message).
 Similarly, changes in the model (via AngularJS $scope.message) reflect in the view
(input field).

31
2. Two-Way Data Binding
Two-way data binding allows changes to be reflected in both the model and the view. In
AngularJS, this is primarily achieved using the ng-model directive.
 Model to View: When the model is updated, the view is automatically updated.
 View to Model: When the user changes the view (like input), the model is
automatically updated.
Example of Two-Way Data Binding with ng-model
<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AngularJS Two-Way Data Binding</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></
script>
</head>
<body>

<div ng-controller="MainController">
<input type="text" ng-model="message"> <!-- Two-way data binding -->
<h1>{{ message }}</h1> <!-- Automatically updates when model changes -->
</div>

<script>
angular.module('myApp', [])
.controller('MainController', function($scope) {
$scope.message = "Hello, AngularJS!";
});
</script>

</body>
</html>
In this example:
 Two-way binding is established using ng-model on the input field.
 Any change made in the input field is automatically reflected in the $scope.message
model.
 Similarly, if the $scope.message in the controller changes, the view (the input field and
the <h1> tag) is automatically updated.

32
Two-Way Data Binding Flow:
1. User Input → Updates the model ($scope.message).
2. Model Update → Automatically updates the view (the input field and <h1>).
3. Data Binding with Directives
In AngularJS, directives can be used to create custom components or enhance the
functionality of native HTML elements. Directives are a great way to manage data binding
effectively.
Example with ng-repeat:
<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AngularJS ng-repeat</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></
script>
</head>
<body>

<div ng-controller="MainController">
<ul>
<li ng-repeat="item in items">{{ item }}</li> <!-- Data Binding with ng-repeat -->
</ul>
</div>

<script>
angular.module('myApp', [])
.controller('MainController', function($scope) {
$scope.items = ['Apple', 'Banana', 'Orange'];
});
</script>

</body>
</html>
Here:
 ng-repeat is used to iterate over the items in the $scope.items array.
 The list updates dynamically when the array changes (e.g., when new items are
added).

33
4. Advantages of Data Binding in AngularJS
1. Automatic Synchronization: No need for manual DOM updates when the model
changes; AngularJS handles it automatically.
2. Simplified Code: Developers don't need to write extra code for updating the view
when the model changes and vice versa.
3. Reduced Boilerplate: Since the view is updated automatically, the code is cleaner and
simpler.
5. Limitations of Data Binding
1. Performance: With large and complex applications, data binding can lead to
performance issues due to the constant updates between the model and view.
2. Digest Cycle: AngularJS uses a mechanism called the digest cycle to monitor changes.
In complex apps with many watchers (which monitor data binding), this can become
slow if not optimized.
3. No Direct DOM Manipulation: AngularJS doesn't directly manipulate the DOM, which
can lead to limitations in some advanced use cases.

Conclusion
AngularJS data binding is a powerful feature that simplifies the synchronization of the model
(data) and the view (UI). By using two-way data binding, developers can ensure that changes
in the model automatically update the view and vice versa, without writing additional code to
manually manipulate the DOM. Although AngularJS has been largely superseded by Angular
2+ (a completely rewritten framework), understanding data binding in AngularJS provides
valuable insight into how modern frameworks manage user interfaces and data flow.

ANGULAR BUILT-IN DIRECTIVES


AngularJS Built-in Directives
In AngularJS, directives are special markers in the DOM (HTML) that extend the functionality of
the HTML elements. They are used to attach behavior to DOM elements, such as dynamically
updating data, iterating over data, conditionally displaying elements, handling user input, and
more.
AngularJS provides a set of built-in directives that cover common use cases for building
dynamic web applications.
Here’s an overview of the most commonly used AngularJS built-in directives:

1. ng-app
The ng-app directive initializes an AngularJS application. It’s the root element of an AngularJS
app, and it tells AngularJS to compile and process the contents within this element.
Example:

34
<html ng-app="myApp">
<body>
<h1>Welcome to AngularJS!</h1>
</body>
</html>
 ng-app="myApp" initializes the AngularJS application and links it to the myApp module.

2. ng-model
The ng-model directive binds the value of an HTML input element (like a text field) to a variable
in the AngularJS controller. This creates a two-way data binding between the view (HTML) and
the model (JavaScript).
Example:
<div ng-app="myApp" ng-controller="MainController">
<input type="text" ng-model="name">
<h1>Hello, {{ name }}!</h1>
</div>

<script>
angular.module('myApp', [])
.controller('MainController', function($scope) {
$scope.name = "John";
});
</script>
 Any changes in the input field automatically update the $scope.name variable, and any
changes to $scope.name in the controller update the input field.

3. ng-bind
The ng-bind directive binds an expression to an HTML element. This is used as an alternative to
{{ expression }} interpolation to avoid the "flash of unstyled content" (FOUC), which can happen
before AngularJS processes the expressions.
Example:
<div ng-app="myApp" ng-controller="MainController">
<h1 ng-bind="message"></h1>
</div>

<script>
angular.module('myApp', [])
.controller('MainController', function($scope) {

35
$scope.message = "Hello, AngularJS!";
});
</script>
 The message from the controller is bound to the <h1> element, and it automatically
updates when the model changes.

4. ng-repeat
The ng-repeat directive is used to repeat an HTML element for each item in a collection (array
or object). It's commonly used to render lists or tables.
Example:
<div ng-app="myApp" ng-controller="MainController">
<ul>
<li ng-repeat="item in items">{{ item }}</li>
</ul>
</div>

<script>
angular.module('myApp', [])
.controller('MainController', function($scope) {
$scope.items = ['Apple', 'Banana', 'Orange'];
});
</script>
 This example will render a list of fruits dynamically using the ng-repeat directive.

5. ng-if
The ng-if directive conditionally includes or removes an HTML element based on the value of an
expression. If the expression evaluates to true, the element is added to the DOM; otherwise, it
is removed.
Example:
<div ng-app="myApp" ng-controller="MainController">
<button ng-click="isVisible = !isVisible">Toggle Message</button>
<p ng-if="isVisible">This message is conditionally displayed!</p>
</div>

<script>
angular.module('myApp', [])
.controller('MainController', function($scope) {
$scope.isVisible = false;

36
});
</script>
 The <p> element will only be displayed when isVisible is true.

6. ng-show / ng-hide
The ng-show and ng-hide directives are used to conditionally show or hide HTML elements
based on the evaluation of an expression. When the expression is true, the element is shown;
when it’s false, the element is hidden.
Example of ng-show:
<div ng-app="myApp" ng-controller="MainController">
<button ng-click="isVisible = !isVisible">Toggle Visibility</button>
<p ng-show="isVisible">This paragraph is visible when `isVisible` is true.</p>
</div>

<script>
angular.module('myApp', [])
.controller('MainController', function($scope) {
$scope.isVisible = false;
});
</script>
 The <p> tag is shown or hidden based on the value of isVisible.
Example of ng-hide:
<p ng-hide="isVisible">This will be hidden when `isVisible` is true.</p>

7. ng-class
The ng-class directive dynamically adds or removes CSS classes from an element based on the
evaluation of an expression.
Example:
<div ng-app="myApp" ng-controller="MainController">
<button ng-click="isActive = !isActive">Toggle Class</button>
<div ng-class="{'active': isActive}">
This div will have the class 'active' when `isActive` is true.
</div>
</div>

<script>
angular.module('myApp', [])
.controller('MainController', function($scope) {

37
$scope.isActive = false;
});
</script>
 The <div> element will dynamically get or remove the active class depending on the
value of isActive.

8. ng-model
The ng-model directive binds the value of an HTML element (like <input>, <select>, or
<textarea>) to a model in the AngularJS controller. It creates a two-way data binding.
Example:
<div ng-app="myApp" ng-controller="MainController">
<input type="text" ng-model="userName">
<p>Hello, {{ userName }}!</p>
</div>

<script>
angular.module('myApp', [])
.controller('MainController', function($scope) {
$scope.userName = 'John';
});
</script>
 The value of the input field (ng-model="userName") is bound to the $scope.userName,
which is reflected in the paragraph text.

9. ng-submit
The ng-submit directive is used to bind an AngularJS function to the form's submit event. It is
used when you need to handle form submission in an AngularJS way.
Example:
<form ng-app="myApp" ng-controller="MainController" ng-submit="submitForm()">
<input type="text" ng-model="userName" required>
<button type="submit">Submit</button>
</form>

<script>
angular.module('myApp', [])
.controller('MainController', function($scope) {
$scope.submitForm = function() {
alert('Form submitted with name: ' + $scope.userName);

38
};
});
</script>
 The ng-submit directive binds the submitForm function to the form's submit event.

10. ng-switch / ng-switch-when / ng-switch-default


The ng-switch directive is used to conditionally display one of several possible HTML elements
based on the value of an expression.
Example:
<div ng-app="myApp" ng-controller="MainController">
<div ng-switch="color">
<div ng-switch-when="red">Red is chosen</div>
<div ng-switch-when="green">Green is chosen</div>
<div ng-switch-when="blue">Blue is chosen</div>
<div ng-switch-default>Default color chosen</div>
</div>
</div>

<script>
angular.module('myApp', [])
.controller('MainController', function($scope) {
$scope.color = 'green';
});
</script>
 The <div> corresponding to the value of color (e.g., green) will be shown, while others
will be hidden.

Conclusion
AngularJS built-in directives provide a lot of flexibility to build dynamic, interactive web
applications with minimal effort. They allow you to easily manipulate the DOM, control data
binding, conditionally display elements, handle user input, and more. Understanding and using
these built-in directives effectively can significantly improve the productivity and scalability of
your AngularJS applications.

ANGULAR CUSTOM DIRECTIVES


AngularJS Custom Directives

39
In AngularJS, custom directives allow you to create reusable components or extend the
functionality of the built-in directives. Custom directives enable you to add your own behavior
to DOM elements, making your AngularJS application more modular and maintainable.
Why Use Custom Directives?
 Reusability: Custom directives allow you to encapsulate and reuse logic across different
parts of your application.
 Modularization: Custom directives help you separate concerns and organize code in a
more modular way.
 Extend HTML: You can create new HTML elements or attributes, making your HTML
templates cleaner and easier to manage.
How to Create Custom Directives in AngularJS?
In AngularJS, a custom directive can be created using the angular.module().directive() method. A
directive can be a DOM element, attribute, class, or comment.
Here is the basic syntax for defining a custom directive:
angular.module('app', [])
.directive('directiveName', function() {
return {
restrict: 'A', // Directive type ('A' for attribute, 'E' for element, 'C' for class, 'M' for comment)
template: '<div>Custom Directive Content</div>',
// Other options like scope, controller, link, etc.
};
});

Example of a Basic Custom Directive


Let's create a simple custom directive called greeting.
Example:
<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AngularJS Custom Directive Example</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body>

<div ng-controller="MainController">
<!-- Use the custom directive -->

40
<greeting></greeting>
</div>

<script>
angular.module('myApp', [])
.controller('MainController', function($scope) {
$scope.message = "Hello from the Controller!";
})
.directive('greeting', function() {
return {
restrict: 'E', // 'E' for element
template: '<h2>{{message}}</h2>', // Display content from the controller
scope: true // Use the parent scope
};
});
</script>

</body>
</html>
Explanation:
 greeting is the name of the custom directive.
 restrict: 'E' means the directive is an element (<greeting></greeting>).
 template: Specifies the HTML to be injected into the directive's element (here, it binds
to the controller's message).
 scope: true: The directive will inherit properties from the parent scope (i.e., the message
from the controller).

Directive Types in AngularJS


When defining a directive, the restrict property tells AngularJS how the directive can be used.
The restrict property can have one or more of the following values:
 E (Element): The directive is used as an element (e.g., <greeting></greeting>).
 A (Attribute): The directive is used as an attribute on an HTML element (e.g., <div
greeting></div>).
 C (Class): The directive is used as a class (e.g., <div class="greeting"></div>).
 M (Comment): The directive is used as a comment (e.g., <!-- greeting -->).
You can also combine these values, like restrict: 'EA', to allow the directive to be used as both an
element and an attribute.

41
Directive Definition Object
When creating a custom directive, you can define several options in the returned object:
1. template: HTML content or the URL of the HTML template to be injected.
2. templateUrl: URL for the HTML template file (useful for separating templates from
JavaScript code).
3. restrict: Defines how the directive is used (E, A, C, or M).
4. scope: Defines how the scope of the directive interacts with the parent scope (true,
false, or an object).
5. controller: Controller for the directive, allowing you to define logic for the directive.
6. link: A function for adding behavior to the directive, often used for DOM manipulation.

Example: Custom Directive with Controller


Let's create a custom directive that includes a controller for more complex behavior.
Example:
<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Custom Directive with Controller</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body>

<div ng-controller="MainController">
<custom-message></custom-message>
</div>

<script>
angular.module('myApp', [])
.controller('MainController', function($scope) {
$scope.user = "John";
})
.directive('customMessage', function() {
return {
restrict: 'E', // Directive is used as an element
scope: {}, // Isolate scope
controller: function($scope) {

42
$scope.message = "Welcome, " + "John!";
},
template: '<h2>{{ message }}</h2>',
};
});
</script>

</body>
</html>
Explanation:
 controller: The directive has a controller that sets up the message property.
 scope: {}: This directive uses an isolated scope, meaning it does not inherit from the
parent scope, and it has its own isolated scope for the directive.
 The directive injects the message into the template, displaying "Welcome, John!".

Using the link Function


The link function provides access to the DOM, where you can manipulate elements, add event
listeners, or initialize any JavaScript functionality after the directive is linked to the DOM.
Example with link Function:
<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Directive with Link Function</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body>

<div ng-controller="MainController">
<button ng-click="changeColor()">Change Background Color</button>
<custom-style></custom-style>
</div>

<script>
angular.module('myApp', [])
.controller('MainController', function($scope) {
$scope.changeColor = function() {

43
$scope.bgColor = $scope.bgColor === 'blue' ? 'green' : 'blue';
};
})
.directive('customStyle', function() {
return {
restrict: 'E',
scope: {
color: '='
},
link: function(scope, element, attrs) {
scope.$watch('color', function(newValue) {
element.css('background-color', newValue);
});
},
template: '<div>Change my background color!</div>'
};
});
</script>

</body>
</html>
Explanation:
 The link function is used to watch for changes in the color scope variable and
dynamically change the background color of the element.
 The background color is updated every time the color property changes.

Isolated Scope in Directives


Isolated scope is useful for directives that need to have their own data and not inherit from the
parent scope. It’s useful in reusable components to avoid unintentional changes to the parent
scope.
scope: {
propertyName: '=' // Two-way binding
}

Summary of Directive Options


 restrict: Defines how the directive can be used (E, A, C, M).
 template: Defines the HTML template to inject.
 templateUrl: URL of an external template.

44
 controller: The controller associated with the directive.
 scope: Defines how the scope is handled (false, true, or an object for isolated scope).
 link: A function to manipulate the DOM or bind event listeners.
 transclude: Allows content projection, passing content from the parent into the
directive's template.

Conclusion
Custom directives in AngularJS are powerful tools for creating reusable components,
encapsulating logic, and organizing code. By understanding how to define and work with
directives, you can create more modular, maintainable, and scalable applications.
IMPLEMENT ANGULAR SERVICES IN WEB APPLICATIONS

45

You might also like