AngularJS Simplified
AngularJS Simplified
'
Suman Das
1.1 What is AngularJS? ------------------------------------------------------------------------------------------ 4
1.2 Why AngularJS? ---------------------------------------------------------------------------------------------- 4
1.3 Getting Started ----------------------------------------------------------------------------------------------- 4
A
ngularJS is a powerful JavaScript framework developed by Google for building dynamic web
applications. It extends HTML with additional attributes and binds data to HTML with
expressions. In this chapter, we will delve into the basics of AngularJS and understand why it's
a popular choice for front-end development.
• Two-way Data Binding: AngularJS synchronizes the model and the view automatically.
Changes to the model are reflected in the view, and vice versa, without the need for manual
intervention.
• Modular Structure: AngularJS encourages the development of modular applications, making
it easier to manage and scale large codebases.
• Dependency Injection: AngularJS provides a built-in dependency injection system, which
promotes code reusability and testability.
• Directives: Directives allow you to extend HTML with custom attributes and behaviours,
making it easier to create reusable components.
• Community Support: AngularJS has a large and active community, which means there are
plenty of resources, tutorials, and third-party libraries available.
• Routing: AngularJS provides a built-in routing mechanism that allows you to define routes for
different views in your application, enabling the creation of single-page applications with
multiple views.
• Testing Support: AngularJS comes with built-in support for unit testing and end-to-end testing,
making it easier to write and maintain test suites for your applications.
Let's dive into building a simple AngularJS application to get a hands-on experience with the framework.
We'll start by setting up a basic HTML file and including AngularJS library:
<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="UTF-8">
<title>AngularJS Demo</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body>
<div ng-controller="MyController">
<h1>{{ greeting }}</h1>
</div>
<script>
angular.module('myApp', [])
.controller('MyController', function ($scope) {
$scope.greeting = 'Hello, AngularJS!';
});
</script>
</body>
</html>
In this code:
That's it! You've created your first AngularJS application. Open the HTML file in a web browser, and you
should see the greeting message "Hello, AngularJS!" displayed on the page.
:
I
n this chapter, we will walk through the process of setting up your development environment and
creating your first AngularJS application. By the end of this chapter, you'll have a solid
understanding of the basic structure of an AngularJS application and how to get started with coding.
Before we begin coding, let's ensure that you have the necessary tools set up in your development
environment. Here's what you'll need:
• Text Editor or IDE: Choose a text editor or an Integrated Development Environment (IDE) for
writing your code. Popular choices include Visual Studio Code, Sublime Text, and WebStorm.
• Web Browser: You'll need a web browser to run and test your AngularJS applications. Google
Chrome, Mozilla Firefox, or Microsoft Edge are commonly used browsers for web development.
• AngularJS Library: Download or include the AngularJS library in your project. You can either
download it from the official website or include it via a Content Delivery Network (CDN) like in
Chapter 1.
Now that your development environment is set up, let's create a simple AngularJS application. We'll
start with a basic HTML file and gradually build upon it:
<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="UTF-8">
<title>My AngularJS App</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"/>
</head>
<body>
<div ng-controller="MyController">
<h1>{{ greeting }}</h1>
</div>
<script>
angular.module('myApp', [])
.controller('MyController', function ($scope) {
$scope.greeting = 'Hello, AngularJS!';
});
</script>
</body>
</html>
Let’s break down the code:
• We start with a basic HTML structure, including the necessary <head> and <body> tags.
• Inside the <head> tag, we include the AngularJS library using a <script> tag. Make sure to
include the correct version of AngularJS.
• Within the <body> tag, we define a <div> element with the ng-controller directive set to
"MyController". This directive associates the controller MyController with this portion of
the HTML.
• Inside the <div> element, we have an <h1> heading element with double curly braces {{
greeting }}. This is an AngularJS expression that will be replaced with the value of the
greeting variable defined in the controller.
• In the <script> tag at the bottom, we define an AngularJS module named myApp using the
angular.module function. Inside this module, we define a controller named MyController
using the controller function. The controller function takes a callback function as an
argument, where we inject the $scope service. We then set the greeting variable on the $scope
object to "Hello, AngularJS!".
• Module: A module is a container for the different parts of an AngularJS application. It is created
using the angular.module function. In our example, we created a module named myApp.
• Controller: A controller is a JavaScript constructor function that is used to augment the
AngularJS scope. It is defined using the controller function. In our example, we defined a
controller named MyController.
• Directive: Directives are markers on a DOM element that tell AngularJS's HTML compiler
($compile) to attach a specified behaviour to that DOM element or even transform the DOM
element and its children. In our example, we used the ng-controller directive to associate the
MyController controller with a portion of the HTML.
:
D
irectives are a fundamental part of AngularJS that allow you to extend HTML with new
attributes and behaviours. In this chapter, we will explore directives in AngularJS, understand
their purpose, and learn how to create and use them effectively.
Directives are markers on a DOM 1element that tell AngularJS's HTML compiler ($compile) to attach a
specified behaviour to that DOM element or even transform the DOM element and its children. They are
a way to teach HTML new tricks!
AngularJS comes with a set of built-in directives that provide common functionalities out of the box.
Some of the most used built-in directives include:
• ng-model: Binds the value of HTML controls (input, select, text area) to application data.
• ng-repeat: Iterates over a collection and repeats a set of HTML elements for each item in the
collection.
• ng-click: Specifies an expression to evaluate when an element is clicked.
• ng-show/ng-hide: Conditionally shows or hides HTML elements based on an expression.
In addition to built-in directives, AngularJS allows you to create custom directives to encapsulate and
reuse UI components and behaviours across your application. Let's create a simple custom directive
called myDirective:
<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="UTF-8">
<title>Custom Directives</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js" />
</head>
<body>
<div ng-controller="MyController">
<my-directive></my-directive>
</div>
<script>
angular.module('myApp', [])
.controller('MyController', function ($scope) {
})
.directive('myDirective', function () {
return {
template: '<h2>This is my custom directive!</h2>'
};
});
1
DOM stands for Document Object Model
</script>
</body>
</html>
Let’s break down the code:
Directives allow you to create reusable components and encapsulate complex behaviours. They help
in keeping your HTML clean and maintainable by abstracting away DOM manipulation and interaction
logic.
:
C
ontrollers are an essential part of AngularJS applications as they provide the application logic
and behaviour. In this chapter, we'll explore controllers in AngularJS, understand their
purpose, and learn how to create and use them effectively.
Controllers in AngularJS are JavaScript functions that are responsible for handling user interactions,
manipulating data, and coordinating the communication between the view and the model. They play a
crucial role in separating concerns within an application by encapsulating the business logic.
Scope Controller
The $scope object is a core concept in AngularJS that serves as the bridge between the controller and
the view. It acts as the model for the view and holds the data that the view will present to the user.
Controllers can communicate with the view by attaching properties and functions to the $scope
object.
When working with controllers in AngularJS, it's essential to follow best practices to maintain a clean
and maintainable codebase:
• Single Responsibility Principle: Each controller should have a single responsibility, focusing
on a specific feature or functionality.
• Thin Controllers, Fat Services: Controllers should be kept thin by moving business logic and
data manipulation into services.
• ControllerAs Syntax: Use the controllerAs syntax to alias controllers in the view, promoting
better readability and avoiding scope-related issues.
• Avoid $scope Inheritance: Minimize the use of nested scopes and avoid inheriting properties
from parent scopes to avoid complexity and potential bugs.
Let's create a simple AngularJS application with a controller to demonstrate how controllers work:
<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="UTF-8">
<title>Controllers</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js" />
</head>
<body>
<div ng-controller="MyController as vm">
<h1>{{ vm.greeting }}</h1>
</div>
<script>
angular.module('myApp', [])
.controller('MyController', function () {
var vm = this;
vm.greeting = 'Hello, AngularJS!';
});
</script>
</body>
</html>
In this code:
Controllers are responsible for initializing the data, defining behaviour, and managing the state of the
application. They play a vital role in the AngularJS architecture by providing the application logic needed
to create dynamic and interactive web applications.
:
S
ervices are a fundamental part of AngularJS applications, providing a way to organize and share
code across different parts of your application. In this chapter, we'll explore services in
AngularJS, understand their purpose, and learn how to create and use them effectively.
Services in AngularJS are singleton objects that perform specific tasks, such as fetching data from a
server, performing calculations, or sharing data between controllers. They are used to encapsulate
reusable functionality and promote code reusability and maintainability.
AngularJS provides several built-in services that cover common tasks and functionalities required in
web applications. Some of the most commonly used built-in services include:
• $http: Provides a simplified interface for making AJAX requests to a server and handling
responses.
• $rootScope: The top-level scope that is available to all AngularJS applications. It can be used
to broadcast and listen for events across different parts of the application.
• $log: Provides a simple logging service that can be used for debugging purposes.
• $timeout: Provides a service that allows you to execute a function after a specified delay.
In addition to built-in services, AngularJS allows you to create custom services to encapsulate and
share functionality across different parts of your application. Let's create a simple custom service
called userService:
angular.module('myApp')
.service('userService', function () {
var users = ['Alice', 'Bob', 'Charlie'];
this.getUsers = function () {
return users;
};
this.addUser = function (user) {
users.push(user);
};
});
In this code:
• We define a new AngularJS service named userService using the service method.
• Inside the service function, we define two methods: getUsers and addUser. These methods
encapsulate the functionality for retrieving a list of users and adding a new user to the list,
respectively.
• The users array is a private variable that is accessible only within the service.
Once a service is defined, it can be injected into controllers, directives, or other services using
AngularJS's dependency injection system. Let's use the userService we created in a controller:
angular.module('myApp')
.controller('UserController', function ($scope, userService) {
$scope.users = userService.getUsers();
• We inject the userService into the controller function using AngularJS's dependency
injection mechanism.
• We call the getUsers method of the userService to retrieve the list of users and assign it to
the $scope.users variable, making it available to the view.
• We define an addUser function on the scope that adds a new user using the addUser method
of the userService.
Services play a crucial role in AngularJS applications by providing a way to share functionality and data
across different parts of the application. They promote code reusability, maintainability, and separation
of concerns, making it easier to manage complex applications.
:
D
ata binding is a powerful feature of AngularJS that enables synchronization of data between the
model and the view. In this chapter, we'll explore data binding in AngularJS, understand its
purpose, and learn how to use it effectively to create dynamic and responsive user interfaces.
Data binding in AngularJS establishes a connection between the model (JavaScript objects) and the
view (HTML elements). Any changes made to the model are automatically reflected in the view, and vice
versa, without the need for manual intervention. This two-way data binding ensures that the view is
always up to date with the underlying data.
In one-way data binding, the data flows from the model to the view. Changes in the model update the
view, but changes in the view do not affect the model. One-way data binding is achieved using AngularJS
expressions ({{ expression }}) and directives like ng-bind.
Two-way data binding allows data to flow in both directions, from the model to the view and from the
view to the model. Changes in the model update the view, and changes in the view update the model
automatically. Two-way data binding is achieved the ng-model directive.
While data binding is a powerful feature, it's essential to use it judiciously to ensure optimal
performance and maintainability of your AngularJS applications. Here are some best practices for
efficient data binding:
• Limit the Use of Watchers: Minimize the number of watchers in your application to reduce the
digest cycle time.
• Use One-time Bindings: Use one-time bindings (::) for data that doesn't change frequently to
avoid unnecessary watch expressions.
• Avoid Complex Expressions: Keep AngularJS expressions simple and avoid complex logic to
improve readability and performance.
• Use ng-model Options: Utilize ng-model options like debounce, updateOn, and
allowInvalid to control the behaviour of two-way data binding.
Let's create a simple example to demonstrate two-way data binding using the ng-model directive
<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="UTF-8">
<title>Data Binding</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js">
</script>
</head>
<body>
<div ng-controller="UserController">
<input type="text" ng-model="user.name">
<h2>Hello, {{ user.name }}!</h2>
</div>
<script>
angular.module('myApp', [])
.controller('UserController', function ($scope) {
$scope.user = {
name: ''
};
});
</script>
</body>a
</html>
In this example:
• We define an input element with the ng-model directive bound to user.name. This
establishes two-way data binding between the input field and the user.name property in the
controller's scope.
• We use an AngularJS expression ({{ user.name }}) to display the value of user.name in
the view.
• When the user types in the input field, the value is automatically updated in the user.name
property of the controller's scope, and the corresponding change is reflected in the view
Data binding is a key feature of AngularJS that simplifies the development of dynamic and responsive
user interfaces. It reduces the amount of boilerplate code needed to keep the view in sync with the
underlying data, resulting in cleaner and more maintainable code.
:
R
outing is an essential aspect of single-page applications (SPAs) that allows users to navigate
between different views or pages without the need for full-page reloads. In this chapter, we'll
explore routing in AngularJS, understand its purpose, and learn how to implement it effectively
to create a seamless navigation experience.
Routing in AngularJS refers to the process of mapping URLs to different views or templates within your
application. It enables users to navigate between different parts of the application by changing the URL
in the address bar, without triggering a full-page refresh.
To implement routing in AngularJS, you need to configure routes that map specific URLs to
corresponding views or templates. This is typically done using the $routeProvider service provided
by the ngRoute module.
<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="UTF-8" />
<title>Routing</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular-route.js">
</script>
</head>
<body>
<div ng-view></div>
<script>
angular
.module("myApp", ["ngRoute"])
.config(function ($routeProvider) {
$routeProvider
.when("/", {
templateUrl: "home.html",
controller: "HomeController",
})
.when("/about", {
templateUrl: "about.html",
controller: "AboutController",
})
.otherwise({ redirectTo: "/" });
})
.controller("HomeController", function () {
// Controller logic for the home view
})
.controller("AboutController", function () {
// Controller logic for the about view
});
</script>
</body>
</html>
In this code:
• We define a new AngularJS module named myApp and include the ngRoute module as a
dependency to enable routing.
• Inside the module's configuration phase, we use the $routeProvider service to configure
routes for different URLs.
• For each route, we specify the URL path, the template URL (or the template itself), and the
controller associated with the view.
• We also define controller functions (HomeController and AboutController) to handle the
logic for each view.
AngularJS allows you to define route parameters and redirects to create dynamic and flexible routing
configurations.
.when('/user/:userId', {
templateUrl: 'user.html',
controller: 'UserController'
})
In this example, :userId is a route parameter that can be accessed within the controller using the
$routeParams service.
.otherwise({ redirectTo: '/' });
The otherwise method specifies a default route to redirect to if the requested URL doesn't match any
of the defined routes.
Route guards and resolvers are advanced features of routing in AngularJS that allow you to control
access to routes and pre-fetch data before navigating to a route.
.when('/profile', {
templateUrl: 'profile.html',
controller: 'ProfileController',
resolve: {
userData: function (UserService) {
return UserService.getUserData();
}
}
})
In this example, the resolve property specifies a resolver function that fetches user data before
navigating to the profile route.
Routing enables users to navigate between different views or pages within a singlepage application,
providing a seamless and interactive user experience.
:
F
orms play a significant role in web applications for capturing user input and submitting data. In
this chapter, we'll explore how AngularJS facilitates form handling and validation, enabling
developers to create interactive and user-friendly forms.
In AngularJS, forms are an integral part of building dynamic web applications. AngularJS provides a set
of directives and services that make it easy to work with forms, handle user input, and perform
validation.
AngularJS allows you to create forms using the <form> element and various form controls such as
<input>, <select>, and <textarea>. You can use directives like ng-model to bind form
controls to properties in your controller
<form name="myForm" ng-submit="submitForm()">
<input type="text" ng-model="formData.username" required>
<input type="password" ng-model="formData.password" required>
<button type="submit">Submit</button>
</form>
In this example, we create a simple form with two input fields for username and password. The ng-
model directive binds the input fields to properties (formData.username and
formData.password) in the controller's scope.
AngularJS provides built-in support for form validation, allowing you to validate user input both on the
client-side and server-side. You can use directives like ng-required, ng-pattern, and ng-
minlength to add validation rules to form controls.
<form name="myForm" ng-submit="submitForm()" novalidate>
<input type="email" ng-model="formData.email" name="email" required>
<div ng-messages="myForm.email.$error" ng-if="myForm.email.$dirty">
<div ng-message="required">Email is required.</div>
<div ng-message="email">Invalid email format.</div>
</div>
<button type="submit">Submit</button>
</form>
In this example, we add validation to an email input field using the ng-email directive and display
error messages using the ng-messages directive.
AngularJS allows you to create custom validation directives to implement complex validation logic that
is not covered by built-in directives. Custom validation directives can be reusable across multiple forms
and provide a clean and modular approach to form validation.
angular.module('myApp')
.directive('passwordMatch', function () {
return {
require: 'ngModel',
link: function (scope, element, attrs, ctrl) {
var otherInput =
document.getElementsByName(attrs.passwordMatch)[0];
ctrl.$validators.passwordMatch = function (modelValue,
viewValue) {
return viewValue === otherInput.value;
};
otherInput.addEventListener('input', function () {
scope.$apply(function () {
ctrl.$validate();
});
});
}
};
});
In this example, we create a custom directive named passwordMatch to validate that two password
fields match each other.
AngularJS provides mechanisms for handling form submission and error handling. You can use the ng-
submit directive to specify a function to be called when the form is submitted, and the $valid and
$invalid properties to check the validity of the form.
angular.module('myApp')
.controller('FormController', function ($scope, $http) {
$scope.submitForm = function () {
if ($scope.myForm.$valid) {
// Form is valid, submit data to server
$http.post('/submit', $scope.formData)
.then(function (response) {
// Handle successful response
}, function (error) {
// Handle error response
});
}
};
});
In this controller, we define a submitForm function that is called when the form is submitted. We
check if the form is valid using the $valid property before submitting the data to the server using the
$http service. 8.6 Forms and Validation in Action.
Forms and validation are crucial aspects of web applications, enabling users to interact with the
application and submit data securely. AngularJS provides a comprehensive set of features for handling
forms and performing validation, making it easy to create interactive and user-friendly forms.
:
H
TTP communication is crucial for modern web applications to interact with servers, fetch data,
and send updates. In this chapter, we'll delve into how AngularJS facilitates HTTP
communication, enabling developers to create robust and data-driven web applications.
HTTP communication in AngularJS allows applications to fetch data from external servers, send data to
servers, and handle responses asynchronously. This enables developers to build dynamic and
interactive web applications that fetch and display data in real-time.
$http
AngularJS provides the $http service, which simplifies making HTTP requests to servers. The $http
service supports various HTTP methods such as GET, POST, PUT, DELETE, etc., and allows developers
to handle responses using promises.
angular.module('myApp')
.controller('UserController', function ($http) {
$http.get('/api/users')
.then(function (response) {
// Handle successful response
console.log(response.data);
})
.catch(function (error) {
// Handle error response
console.error('Error:', error);
});
});
In this example, we use the $http.get method to fetch user data from the server. We handle the
response using promises, and in case of an error, we catch and handle it accordingly
AngularJS interceptors are middleware functions that can be used to intercept HTTP requests and
responses globally within an application. Interceptors are useful for adding custom headers, logging
requests, or handling errors uniformly across multiple HTTP requests.
angular.module('myApp')
.factory('AuthInterceptor', function ($q, $location) {
return {
request: function (config) {
// Add authorization token to headers
config.headers.Authorization = 'Bearer ' + authToken;
return config;
},
responseError: function (response) {
if (response.status === 401) {
// Redirect to login page
$location.path('/login');
}
return $q.reject(response);
}
};
})
.config(function ($httpProvider) {
$httpProvider.interceptors.push('AuthInterceptor');
});
In this example, we define an interceptor named AuthInterceptor that adds an authorization token
to the request headers and redirects to the login page in case of a 401 unauthorized response.
Cross-Origin Resource Sharing (CORS) is a security feature implemented by web browsers that restricts
HTTP requests from scripts to resources in a different origin. AngularJS provides support for handling
CORS requests and responses using configuration options such as withCredentials.
$http.get('https://api.example.com/data', { withCredentials: true })
.then(function (response) {
// Handle successful response
})
.catch(function (error) {
// Handle error response
});
In this example, we make a CORS request to an external API by setting the withCredentials option
to true.
HTTP communication is essential for fetching data from servers, submitting form data, and interacting
with external APIs in web applications. AngularJS simplifies HTTP communication with its $http
service, interceptors, and support for handling CORS requests, making it easier to build robust and
data-driven applications.