0% found this document useful (0 votes)
23 views41 pages

BEIT 6 Angular JS in Details ClassNotes Unit 3 Bha - 250210 - 133356

The document provides an in-depth overview of AngularJS, focusing on modules, controllers, and filters. It explains how to create and manage modules and controllers, the role of $scope in data binding, and introduces the Controller As syntax for cleaner code. Additionally, it covers built-in filters for data formatting and the basics of handling forms and validations in AngularJS applications.

Uploaded by

niravmaru25
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views41 pages

BEIT 6 Angular JS in Details ClassNotes Unit 3 Bha - 250210 - 133356

The document provides an in-depth overview of AngularJS, focusing on modules, controllers, and filters. It explains how to create and manage modules and controllers, the role of $scope in data binding, and introduces the Controller As syntax for cleaner code. Additionally, it covers built-in filters for data formatting and the basics of handling forms and validations in AngularJS applications.

Uploaded by

niravmaru25
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

Advanced Web Programming-3161611 Angular JS in Details

Unit-3-Angular JS in Details

Modules in AngularJS

A module in AngularJS is a container for the various parts of your application, such as
controllers, services, filters, and directives. It defines the boundaries of an AngularJS
application and is used to organize your code in a modular way.

Creating a Module

A module is created using the angular.module() function. The first argument is the name of
the module, and the second argument is an array of dependencies (other modules) that your
module might require.

Basic Syntax:

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

• 'myApp' is the name of the module.


• [] is the list of dependencies (empty in this case, meaning no other modules are being
imported).

Module Example

var app = angular.module('myApp', []); // Define the 'myApp' module

// Controller for the 'myApp' module

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

$scope.message = "Hello from AngularJS!";

});

Explanation:

• The app variable holds the module, 'myApp' is the name of the module, and it's
associated with the MainController.

• The controller (MainController) is tied to the module and manages the data for the
view (in this case, the message).

Prof.Bharat Vainsh, Information Technology, GEC Bhavnagar 1


Advanced Web Programming-3161611 Angular JS in Details

Controllers in AngularJS

In AngularJS, controllers are JavaScript functions that are used to control the data and logic
of the application.

They are responsible for managing the scope (which is the context for expressions) and
handling the interactions between the view (HTML) and the model (JavaScript data).

Controllers in AngularJS allow you to:


1. Define the business logic for your application.
2. Bind data to the view.
3. Respond to user inputs and events (like clicks or form submissions).
Basic Structure of a Controller in AngularJS
A controller in AngularJS is defined using the controller () method of an AngularJS module.
It takes two arguments:
1. The name of the controller.
2. A function that defines the controller logic.

Syntax:

angular.module('myApp', [])
.controller('ControllerName', function($scope) {
// Controller logic here
$scope.property = 'Hello, AngularJS!';
});

• $scope is the object used to pass data between the controller and the view.
• The controller function defines the logic, and any properties or methods added to
$scope become available in the view.

Example of a Simple AngularJS Controller

<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="UTF-8">
<title>AngularJS Controller Example</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> <!-- Displaying data from the controller -->
<button ng-click="changeMessage()">Click me</button> <!-- Calling a method from the
controller -->
</div>

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

// Define the controller


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

Prof.Bharat Vainsh, Information Technology, GEC Bhavnagar 2


Advanced Web Programming-3161611 Angular JS in Details

// Define a property on the scope


$scope.message = "Hello, AngularJS!";

// Define a method on the scope


$scope.changeMessage = function() {
$scope.message = "You clicked the button!";
};
});
</script>

</body>
</html>
Explanation:

• The controller MainController is associated with the HTML view using ng-
controller="MainController".

• $scope.message is initialized with the string "Hello, AngularJS!", which is then


displayed inside the <h1> tag using AngularJS expression binding ({{ message }}).

• $scope.changeMessage() is a function that changes the value of message when the


button is clicked. This is handled by the ng-click directive.

How Controllers Work with Scope

In AngularJS, scope is a special JavaScript object that allows you to bind data between the
controller and the view. The scope object acts as a communication bridge between the view
(HTML) and the controller (JavaScript).

• Controller Logic (JavaScript):


o Variables and functions that you want to make available in the view are defined
on the $scope object.
• View (HTML):
o You can access properties or call methods defined in the controller through the
scope using AngularJS expressions, like {{ message }} or ng-
click="someMethod()".

Example with Two-Way Data Binding:

<div ng-controller="MainController">
<input type="text" ng-model="userInput">
<p>You entered: {{ userInput }}</p>
</div>

• ng-model="userInput" binds the input field to the userInput property on the $scope
object.

• As the user types in the input field, the userInput property is updated on the $scope,
and the change is reflected in the view instantly due to AngularJS’s two-way data binding.

Prof.Bharat Vainsh, Information Technology, GEC Bhavnagar 3


Advanced Web Programming-3161611 Angular JS in Details

Controller Scope vs. Global Scope

 Controller Scope ($scope): The controller scope is local to the controller. It is specific to
the view and the controller it is associated with.
 Data in the $scope is available to the view only within the scope of the controller where
it’s defined.
 It is used to bind data between the view and the controller for that specific part of the
application.
 Global Scope (Window Object): Global variables are accessible throughout the entire
application and not bound to any specific controller. They can lead to conflicts and errors
in large applications, so it’s generally advised to avoid using them.
 AngularJS uses dependency injection to manage the scope and keep things modular.

Controller as Syntax

In AngularJS, Controller As syntax is an alternative to using $scope. This pattern makes the
code cleaner, and it avoids potential issues with scope inheritance.

Instead of using $scope, you can assign your controller logic to a property (often vm, for
“view model”) and use the controller’s property in the view.

Example with Controller As Syntax:

<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="UTF-8">
<title>Controller As Example</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body>

<div ng-controller="MainController as vm">


<h1>{{ vm.message }}</h1>
<button ng-click="vm.changeMessage()">Click me</button>
</div>

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

app.controller('MainController', function() {
var vm = this; // Use "this" to reference the controller

vm.message = "Hello, AngularJS!";

vm.changeMessage = function() {
vm.message = "You clicked the button!";
};
});
</script>
</body>
</html>

Prof.Bharat Vainsh, Information Technology, GEC Bhavnagar 4


Advanced Web Programming-3161611 Angular JS in Details

Explanation:

• In this example, vm (ViewModel) is used to store the properties and methods of the
controller.
• In the view, vm.message and vm.changeMessage() are accessed instead of $scope.
Advantages of Controller As Syntax:
• Cleaner code.
• Avoids the problem of $scope inheritance in nested controllers.
• More natural in terms of JavaScript object-oriented principles (using this).

Controller with Dependency Injection

In AngularJS, controllers can also receive dependencies via dependency injection. This
means that AngularJS can automatically provide required services, such as $http (for making
API requests), $routeParams (for routing), and custom services.

Example of Controller with Dependency Injection:

angular.module('myApp', [])
.controller('MainController', function($scope, $http) {
$scope.message = "Loading data...";

$http.get('https://jsonplaceholder.typicode.com/users')
.then(function(response) {
$scope.users = response.data;
$scope.message = "Users loaded successfully!";
})
.catch(function(error) {
$scope.message = "Error loading data.";
});
});

Explanation:
• $http is injected into the controller and used to make an API request.
• The then() method is called when the data is successfully retrieved, and the
$scope.users is populated with the response.
Conclusion
• Controllers in AngularJS are JavaScript functions that control the data and behavior of
a part of your application.
• They are responsible for managing the $scope, which binds data between the model
(JavaScript) and the view (HTML).
• AngularJS allows you to define logic in controllers, handle user inputs, and make the
application more dynamic with features like two-way data binding.
• Controller As syntax is an alternative to using $scope, providing a cleaner way to
define and use controller logic.

Prof.Bharat Vainsh, Information Technology, GEC Bhavnagar 5


Advanced Web Programming-3161611 Angular JS in Details

Filters in AngularJS

In AngularJS, filters are used to format data in the view. They are applied to expressions to
modify the output in a simple and declarative way.

Filters allow you to transform data before it is displayed to the user, making it more readable
or usable.

Built-in Filters in AngularJS

AngularJS comes with a variety of built-in filters for formatting and transforming data:

1. currency

 Purpose: Formats a number as a currency value.


 Syntax: {{ expression | currency [ :symbol ] [ :fractionSize ] }}
 Example:

<p>{{ 1234.56 | currency }}</p>


<!-- Output: $1,234.56 (default symbol is "$") -->

 You can customize the currency symbol and the number of decimal places:

<p>{{ 1234.56 | currency:'€':2 }}</p>


<!-- Output: €1,234.56 -->

2. date

 Purpose: Formats a date to a specific format.


 Syntax: {{ expression | date:format }}
 Example:

<p>{{ '2025-01-29' | date:'fullDate' }}</p>


<!-- Output: Wednesday, January 29, 2025 -->

 Common date formats:


o 'shortDate': 1/29/25
o 'mediumDate': Jan 29, 2025
o 'fullDate': Wednesday, January 29, 2025
o 'longDate': January 29, 2025

3. filter

 Purpose: Filters an array of data based on a search term or criteria.


 Syntax: {{ expression | filter:searchExpression }}
 Example:

<ul>
<li ng-repeat="item in items | filter:searchTerm">{{ item }}</li>
</ul>

If items = ['apple', 'banana', 'grape', 'orange'] and searchTerm = 'ap', it will filter the
array and show apple and grape.

Prof.Bharat Vainsh, Information Technology, GEC Bhavnagar 6


Advanced Web Programming-3161611 Angular JS in Details

4. json

 Purpose: Converts a JavaScript object or array to a JSON string.


 Syntax: {{ expression | json }}
 Example:

<pre>{{ {name: 'John', age: 30} | json }}</pre>


<!-- Output: {"name":"John","age":30} -->
5. limitTo

 Purpose: Limits the length of an array or string to a specified number of items or


characters.
 Syntax: {{ expression | limitTo:limit }}
 Example (array):

<ul>
<li ng-repeat="item in items | limitTo:2">{{ item }}</li>
</ul>
<!-- Output: only the first 2 items from the array -->

 Example (string):

<p>{{ 'Hello AngularJS' | limitTo:5 }}</p>


<!-- Output: Hello -->

6. lowercase

 Purpose: Converts a string to lowercase.


 Syntax: {{ expression | lowercase }}
 Example:

<p>{{ 'HELLO' | lowercase }}</p>


<!-- Output: hello -->
7. uppercase

 Purpose: Converts a string to uppercase.


 Syntax: {{ expression | uppercase }}
 Example:

<p>{{ 'hello' | uppercase }}</p>


<!-- Output: HELLO -->

8. number

 Purpose: Formats a number with commas and a specified number of decimal places.
 Syntax: {{ expression | number : fractionSize }}
 Example:

<p>{{ 1234.5678 | number:2 }}</p>


<!-- Output: 1,234.57 -->

Prof.Bharat Vainsh, Information Technology, GEC Bhavnagar 7


Advanced Web Programming-3161611 Angular JS in Details

9. orderBy

 Purpose: Orders an array based on one or more expressions.


 Syntax: {{ expression | orderBy : expression : reverse }}
 Example:

<ul>
<li ng-repeat="item in items | orderBy: 'name'">{{ item.name }}</li>
</ul>
You can also reverse the order:
<ul>
<li ng-repeat="item in items | orderBy: 'name': true">{{ item.name }}</li>
</ul>

Using Filters in AngularJS Controllers

Filters can also be used programmatically in the controller. You can use $filter to apply
filters to data.

Example of Using $filter in a Controller


app.controller('myCtrl', function($scope, $filter) {
$scope.number = 1234.5678;
$scope.currency = $filter('currency')($scope.number, '€', 2);
});

In the view, you can use it like this:

<p>{{ currency }}</p>


<!-- Output: €1,234.57 -->

Summary of Common AngularJS Filters

Filter Purpose Example

currency Formats a number as currency. `{{ 1234.56

date Formats a date to a specified format. `{{ '2025-01-29'

filter Filters an array based on a search term. `{{ items

json Converts an object to a JSON string. `{{ {name: 'John'}

limitTo Limits the length of a string or array. `{{ 'hello'

lowercase Converts a string to lowercase. `{{ 'HELLO'

uppercase Converts a string to uppercase. `{{ 'hello'

number Formats a number with commas and decimals. `{{ 1234.5678

orderBy Orders an array based on a specific expression. `{{ items

Prof.Bharat Vainsh, Information Technology, GEC Bhavnagar 8


Advanced Web Programming-3161611 Angular JS in Details

AngularJS Forms and Validations

In AngularJS, forms are an essential part of web applications, and Angular provides powerful
tools for handling form controls, validation, and feedback.

AngularJS simplifies form management by providing directives, two-way data binding, and
validation mechanisms.

It offers a comprehensive solution for handling user input, form validation, and ensuring that
data is correctly formatted before submission.

Basic Form Handling in AngularJS

1. Creating a Basic Form

In AngularJS, forms are created using standard HTML <form> tags, but AngularJS adds
directives to handle data binding, validation, and other functionalities.

Example:

<form name="myForm" ng-submit="submitForm()">


<label for="username">Username:</label>
<input type="text" name="username" ng-model="user.username" required>
<span ng-show="myForm.username.$dirty && myForm.username.$invalid">Username is
required.</span>

<label for="email">Email:</label>
<input type="email" name="email" ng-model="user.email" required>
<span ng-show="myForm.email.$dirty && myForm.email.$invalid">Valid email is
required.</span>

<button type="submit" ng-disabled="myForm.$invalid">Submit</button>


</form>

 ng-model: Binds the input element to a property in the scope (here, user.username
and user.email).
 ng-submit: Specifies the function to be called when the form is submitted.
 name: The name attribute is essential to make AngularJS track the form field's state.

Prof.Bharat Vainsh, Information Technology, GEC Bhavnagar 9


Advanced Web Programming-3161611 Angular JS in Details

Form Validation in AngularJS

AngularJS provides several built-in directives to handle form validation.

1. Built-in Validators

Angular provides several built-in validators like required, minlength, maxlength, pattern, etc.

 required: Makes a field mandatory.


 minlength: Specifies the minimum length for a field.
 maxlength: Specifies the maximum length for a field.
 pattern: Validates the input based on a regular expression.

Example:

<form name="myForm" ng-submit="submitForm()">


<label for="username">Username:</label>
<input type="text" name="username" ng-model="user.username" required minlength="3">
<span ng-show="myForm.username.$dirty && myForm.username.$invalid">Username is
required and must be at least 3 characters long.</span>

<label for="email">Email:</label>
<input type="email" name="email" ng-model="user.email" required>
<span ng-show="myForm.email.$dirty && myForm.email.$invalid">Valid email is
required.</span>

<button type="submit" ng-disabled="myForm.$invalid">Submit</button>


</form>

2. Form State

AngularJS provides a variety of properties for tracking the form's state, such as $valid,
$invalid, $dirty, $pristine, and $submitted.

 $valid: True if the form is valid (all controls are valid).


 $invalid: True if the form is invalid (one or more controls are invalid).
 $dirty: True if the control has been modified.
 $pristine: True if the control has not been modified (the default state).
 $submitted: True if the form has been submitted.

Example of Form State Check:

<form name="myForm" ng-submit="submitForm()">


<label for="username">Username:</label>
<input type="text" name="username" ng-model="user.username" required>
<span ng-show="myForm.username.$dirty && myForm.username.$invalid">Username is
required.</span>

<button type="submit" ng-disabled="myForm.$invalid">Submit</button>

<p ng-show="myForm.$submitted && myForm.$valid">Form submitted successfully!</p>


</form>

Prof.Bharat Vainsh, Information Technology, GEC Bhavnagar 10


Advanced Web Programming-3161611 Angular JS in Details

Custom Validators in AngularJS

Sometimes, you may need to create your own custom validation logic. AngularJS allows you
to define custom validators to check specific conditions.

Example of a Custom Validator

You can create a custom validator by adding a function to the $validators object in
AngularJS.

1. Custom Validator for a Valid Age:

app.controller('FormController', function($scope) {
$scope.checkAge = function(age) {
return age >= 18; // Validate that age is at least 18
};
});

2. Custom Validator Usage in HTML:

<form name="myForm" ng-submit="submitForm()">


<label for="age">Age:</label>
<input type="number" name="age" ng-model="user.age" ng-required="true" ng-
pattern="/^\d+$/" ng-change="checkAge(user.age)">
<span ng-show="myForm.age.$error.required">Age is required.</span>
<span ng-show="myForm.age.$error.pattern">Please enter a valid number.</span>
<span ng-show="myForm.age.$valid">Age is valid.</span>
<button type="submit" ng-disabled="myForm.$invalid">Submit</button>
</form>

In the example, the custom function checkAge checks that the age is at least 18. You could
also write a custom validator that checks for complex conditions like ensuring the format of
the input or checking a range.

Asynchronous Validation

In some cases, you may need to perform asynchronous validation (such as checking whether
a username is already taken). AngularJS supports asynchronous validators.

Example of Asynchronous Username Validator:

You can create a custom asynchronous validator using $http to check the availability of a
username:

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


$scope.checkUsername = function(username) {
return $http.get('/checkUsername/' + username)
.then(function(response) {
return response.data.isAvailable; // Assume response contains a flag 'isAvailable'
}, function() {
return false; // Username is taken
});
};

Prof.Bharat Vainsh, Information Technology, GEC Bhavnagar 11


Advanced Web Programming-3161611 Angular JS in Details

});

Usage in HTML:

<form name="myForm" ng-submit="submitForm()">


<label for="username">Username:</label>
<input type="text" name="username" ng-model="user.username" ng-required="true" ng-
change="checkUsername(user.username)">
<span ng-show="myForm.username.$invalid && myForm.username.$dirty">Username is
unavailable.</span>
<button type="submit" ng-disabled="myForm.$invalid">Submit</button>
</form>

Displaying Validation Messages

You can display validation messages dynamically based on the form state or individual
control states using the ng-show directive.

Example:
<form name="myForm" ng-submit="submitForm()">
<label for="email">Email:</label>
<input type="email" name="email" ng-model="user.email" required>
<span ng-show="myForm.email.$dirty && myForm.email.$invalid">
Valid email is required.
</span>

<button type="submit" ng-disabled="myForm.$invalid">Submit</button>


</form>

Here:

 If the email field is invalid (and dirty), a message is displayed.


 If the form is invalid, the submit button is disabled.

Summary

AngularJS provides a robust way to handle forms and validation, offering:

 Two-way data binding with ng-model.


 Built-in form validation with directives like required, minlength, maxlength, and
pattern.
 Validation state tracking with properties like $valid, $invalid, $dirty, and $pristine.
 Custom validators for complex logic and asynchronous validation (e.g., checking
for existing usernames).
 Flexible ways to display validation messages based on form and input state.

Prof.Bharat Vainsh, Information Technology, GEC Bhavnagar 12


Advanced Web Programming-3161611 Angular JS in Details

AngularJS Services

In AngularJS, services are reusable components that provide specific functionality to your
application.

Services can be used to share data, logic, or business functions across multiple controllers,
directives, and other parts of the application.

They are a fundamental building block in AngularJS for managing data and business logic in
a modular and maintainable way.

What Are Services in AngularJS?

Services in AngularJS are singleton objects that are used to share data and logic across the
application. They can be used to:

 Handle HTTP requests.


 Manage application-level data.
 Share state across different components.
 Encapsulate reusable business logic.

They help separate concerns, making your code more modular, testable, and maintainable.

AngularJS services can be created using different ways, including:

1. Factory
2. Service
3. Provider

Each method has its own use cases, but they all serve the same basic purpose: to provide
reusable code across the application.

Prof.Bharat Vainsh, Information Technology, GEC Bhavnagar 13


Advanced Web Programming-3161611 Angular JS in Details

Creating Services in AngularJS

1. Using service

The service method is the most commonly used way to define a service in AngularJS. When
you use service, AngularJS creates a constructor function for the service, and instances of the
service are created using new.

app.service('myService', function() {
this.message = "Hello from Service!";

this.getMessage = function() {
return this.message;
};
});

 myService is a service that provides a method getMessage() which returns a message.


 The this keyword is used to define properties and methods of the service.

Usage in Controller:

app.controller('myCtrl', function($scope, myService) {


$scope.message = myService.getMessage();
});

In the HTML:

<p>{{ message }}</p> <!-- Output: Hello from Service! -->

2. Using factory

The factory method is another common way to define services. Unlike service, the factory
method allows you to return an object or function that is injected into the controller.

factory is more flexible and provides more control over the creation of service objects.

app.factory('myFactory', function() {
var service = {};
service.message = "Hello from Factory!";

service.getMessage = function() {
return service.message;
};

return service; // Return the service object


});

In this case, myFactory is a factory that returns an object with a getMessage() method.

Prof.Bharat Vainsh, Information Technology, GEC Bhavnagar 14


Advanced Web Programming-3161611 Angular JS in Details

Usage in Controller:

app.controller('myCtrl', function($scope, myFactory) {


$scope.message = myFactory.getMessage();
});

In the HTML:

<p>{{ message }}</p> <!-- Output: Hello from Factory! -->

3. Using provider

The provider method is the most configurable and advanced way to define a service in
AngularJS.

It allows you to define a service and configure it before it’s used in your application. You
usually use provider when you need to configure your service during the config phase of the
application.

app.provider('myProvider', function() {
var message = "Default Message";

this.setMessage = function(newMessage) {
message = newMessage;
};

this.$get = function() {
return {
getMessage: function() {
return message;
}
};
};
});

In this example:

 setMessage allows you to configure the service's message before the application
starts.
 $get is the function that AngularJS uses to create an instance of the service.

Configuring the Provider:

app.config(function(myProvider) {
myProvider.setMessage("Hello from Provider!");
});

Prof.Bharat Vainsh, Information Technology, GEC Bhavnagar 15


Advanced Web Programming-3161611 Angular JS in Details

Using the Provider in the Controller:

app.controller('myCtrl', function($scope, myProvider) {


$scope.message = myProvider.getMessage();
});

In the HTML:

<p>{{ message }}</p> <!-- Output: Hello from Provider! -->

Common Use Cases for Services

1. Handling HTTP Requests

A common use of AngularJS services is to manage HTTP requests to a backend API using
the $http service.

Example:

app.service('dataService', function($http) {
this.getData = function() {
return $http.get('https://jsonplaceholder.typicode.com/posts');
};
});

In the controller:

app.controller('myCtrl', function($scope, dataService) {


dataService.getData().then(function(response) {
$scope.posts = response.data;
});
});

This service makes an HTTP GET request and returns the response as a promise, which can
then be handled in the controller.

2. Sharing State Across Controllers

You can use services to share state (data) between multiple controllers. This is useful when
you need to pass data between components that don’t have direct access to each other.

Example:

app.service('userService', function() {
var user = {};

this.setUser = function(userData) {
user = userData;
};

this.getUser = function() {
return user;

Prof.Bharat Vainsh, Information Technology, GEC Bhavnagar 16


Advanced Web Programming-3161611 Angular JS in Details

};
});

In one controller:

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


userService.setUser({ name: 'John', age: 30 });
});

In another controller:

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


$scope.user = userService.getUser();
});

This allows different controllers to share and update user information without direct
dependency between them.

Service Methods and $injector

Service Methods: Services typically expose methods that can be used to encapsulate logic.
These methods can be called by the controllers or other components.

Dependency Injection ($injector): AngularJS uses dependency injection to inject services


into controllers, directives, or other services.

You don't need to manually instantiate services; Angular automatically handles that for you.
However, you can also use $injector to manually get services, although it's not common in
most cases.

Summary of Creating Services in AngularJS

Method Description Usage Example

Defines a service using a constructor function. app.service('myService', function()


service
More commonly used in AngularJS. {...});

Defines a service by returning an object or app.factory('myFactory', function()


factory
function. More flexible. {...});

Most configurable option. Used when you need app.provider('myProvider',


provider
to configure services before use. function() {...});

Prof.Bharat Vainsh, Information Technology, GEC Bhavnagar 17


Advanced Web Programming-3161611 Angular JS in Details

AngularJS Events

In AngularJS, events allow you to handle user interactions and other activities within the
application. AngularJS provides event directives, like ng-click, ng-change, ng-submit, etc.,
for handling common user actions such as clicks, form submissions, and more.

It also offers a set of built-in events and allows you to create custom events for better control
over your application.

AngularJS uses two-way data binding, meaning when an event occurs and changes the
model, the view is automatically updated, and vice versa.

Types of Events in AngularJS

1. DOM Events (User Interactions)

These events are typically triggered by user actions like clicks, mouse movements, keyboard
inputs, etc. AngularJS provides directives for handling these events in a declarative manner.

Common AngularJS Event Directives:

 ng-click: Handles a click event.


 ng-change: Triggers when an input field value changes.
 ng-submit: Handles form submissions.
 ng-mouseover: Triggered when the mouse is over an element.
 ng-keyup: Triggered when a key is released.

Example of DOM Events:

<div ng-app="myApp" ng-controller="myCtrl">


<button ng-click="clickHandler()">Click Me</button>
<input type="text" ng-model="name" ng-change="nameChanged()" placeholder="Enter
your name">
<form ng-submit="submitForm()">
<input type="text" ng-model="formData.name" placeholder="Enter your name">
<button type="submit">Submit</button>
</form>
</div>

In the controller:

angular.module('myApp', [])
.controller('myCtrl', function($scope) {
$scope.clickHandler = function() {
alert('Button clicked!');
};

$scope.nameChanged = function() {
console.log('Name changed:', $scope.name);
};

Prof.Bharat Vainsh, Information Technology, GEC Bhavnagar 18


Advanced Web Programming-3161611 Angular JS in Details

$scope.submitForm = function() {
alert('Form submitted with name: ' + $scope.formData.name);
};
});

 ng-click: Triggers clickHandler() when the button is clicked.


 ng-change: Triggers nameChanged() whenever the input value changes.
 ng-submit: Handles form submission and triggers submitForm().

2. Scope Events (Within Controllers)

In addition to DOM events, AngularJS also allows you to manage custom events at the scope
level, which can be broadcast across controllers, emit within controllers, and listen for
events.

Event Propagation Methods in AngularJS:

 $emit: Sends an event downwards from the current scope to its parent scope.
 $broadcast: Sends an event upwards from the current scope to all its child scopes.
 $on: Listens for an event on a scope.

Example of $emit, $broadcast, and $on:

angular.module('myApp', [])
.controller('parentCtrl', function($scope) {
$scope.$on('childEvent', function(event, data) {
console.log('Parent received childEvent with data:', data);
});

$scope.sendToChild = function() {
$scope.$broadcast('parentEvent', 'Hello from Parent!');
};
})
.controller('childCtrl', function($scope) {
$scope.$on('parentEvent', function(event, data) {
console.log('Child received parentEvent with data:', data);
});

$scope.triggerEvent = function() {
$scope.$emit('childEvent', 'Hello from Child!');
};
});

In HTML:

<div ng-app="myApp">
<div ng-controller="parentCtrl">
<button ng-click="sendToChild()">Send to Child</button>
</div>

<div ng-controller="childCtrl">
<button ng-click="triggerEvent()">Send to Parent</button>
</div>

Prof.Bharat Vainsh, Information Technology, GEC Bhavnagar 19


Advanced Web Programming-3161611 Angular JS in Details

</div>

 $emit: Used by the child controller to send an event to its parent scope.
 $broadcast: Used by the parent controller to send an event to all child scopes.

When the child controller emits an event ($emit), the parent controller listens to it using $on.
Similarly, the parent controller can broadcast an event, and the child controller listens for that
event.

3. AngularJS Custom Events

You can create custom events to respond to specific actions or triggers within your AngularJS
application. For example, you may want to listen for a custom event when a user submits a
form, or a complex UI interaction occurs.

Example of a Custom Event:

angular.module('myApp', [])
.controller('myCtrl', function($scope, $timeout) {
$scope.triggerCustomEvent = function() {
// Custom event trigger
$scope.$broadcast('customEvent', { message: 'This is a custom event!' });
};

$scope.$on('customEvent', function(event, data) {


console.log('Custom Event Received:', data.message);
});

$timeout(function() {
$scope.triggerCustomEvent();
}, 3000); // Trigger custom event after 3 seconds
});

In HTML:

<div ng-app="myApp" ng-controller="myCtrl">


<button ng-click="triggerCustomEvent()">Trigger Custom Event</button>
</div>

In this example:

 A custom event is broadcasted using $broadcast when the button is clicked.


 The custom event is listened to with $on, and its message is logged in the console.

Prof.Bharat Vainsh, Information Technology, GEC Bhavnagar 20


Advanced Web Programming-3161611 Angular JS in Details

Built-in AngularJS Events

AngularJS has several built-in events that you can use in your application for handling
specific scenarios.

 $destroy: Triggered when a scope is destroyed (usually when a controller or directive


is removed).
 $routeChangeStart, $routeChangeSuccess, $routeChangeError: Triggered when
the route changes.
 $locationChangeStart, $locationChangeSuccess: Triggered when the location
(URL) changes.
 $viewContentLoaded: Triggered when the view content has been loaded.

For example, if you want to listen for route changes:

angular.module('myApp', [])
.run(function($rootScope) {
$rootScope.$on('$routeChangeStart', function(event, next, current) {
console.log('Route is changing...');
});
});

Summary of AngularJS Events

Method Description Use Case

Triggered when an element is


ng-click Button or link clicks.
clicked.

Triggered when a model value


ng-change Input or textarea change.
changes.

Triggered when a form is


ng-submit Form submission handling.
submitted.

Propagates an event upward


$emit Send events to parent controllers.
from the current scope.

Propagates an event downward Send events to child controllers or


$broadcast
to child scopes. directives.

Listens for events broadcasted from


$on Listens for an event on a scope.
parents or emitted by children.

Handle route change logic in the


$routeChange* Triggered on route changes.
application.

Triggered when the URL or


$locationChange* Handle logic when the URL changes.
location changes.

Prof.Bharat Vainsh, Information Technology, GEC Bhavnagar 21


Advanced Web Programming-3161611 Angular JS in Details

AngularJS HTML DOM

In AngularJS, the HTML DOM (Document Object Model) is manipulated using directives
and bindings, enabling dynamic interaction between the view (HTML) and the model
(JavaScript).

Unlike traditional web development, where JavaScript directly interacts with the DOM,
AngularJS provides a declarative approach by extending HTML with custom attributes and
tags to manage DOM behavior.

AngularJS uses two-way data binding to synchronize the view and the model, making DOM
manipulation automatic and seamless.

With AngularJS, you primarily interact with the DOM through directives, which are special
markers added to HTML elements. These directives allow you to create dynamic and
interactive pages.

Key Concepts for Working with HTML DOM in AngularJS

1. Directives in AngularJS

Directives are special attributes or tags in AngularJS that extend HTML and provide behavior
to DOM elements. AngularJS has both built-in directives and allows you to create your own
custom directives.

Common Built-in Directives:

 ng-model: Creates a two-way data binding between the view (HTML) and the model
(JavaScript).
 ng-bind: Binds the value of a variable to an HTML element, displaying the value
dynamically.
 ng-repeat: Repeats an element or a set of elements for each item in an array.
 ng-if: Conditionally includes an element in the DOM based on an expression's truth
value.
 ng-show / ng-hide: Toggles the visibility of an element based on a condition.
 ng-click: Attaches a click event handler to an element.
 ng-class: Dynamically adds or removes CSS classes based on an expression.

Examples of Directives:

ng-model (Data Binding):

<input type="text" ng-model="name">


<p>Hello, {{ name }}!</p>

Here, ng-model binds the input field to the name variable. As the user types, the name
variable is updated automatically, and the text Hello, {{ name }}! is updated in real-time.

Prof.Bharat Vainsh, Information Technology, GEC Bhavnagar 22


Advanced Web Programming-3161611 Angular JS in Details

ng-repeat (Repeating Elements):

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

Here, ng-repeat repeats the <li> element for each item in the items array.

ng-if (Conditional Display):

<div ng-if="isVisible">This element is visible!</div>

The element will only be included in the DOM if the isVisible condition evaluates to true.

2. Two-Way Data Binding in AngularJS

One of the most powerful features of AngularJS is two-way data binding, which
automatically synchronizes the data between the view (HTML) and the model (JavaScript).
This means that any changes made to the input in the view are reflected in the model, and any
changes made to the model are reflected in the view.

Example of Two-Way Data Binding:

<div ng-app="myApp" ng-controller="myCtrl">


<input type="text" ng-model="name">
<p>{{ name }}</p>
</div>

In the AngularJS controller:

angular.module('myApp', [])
.controller('myCtrl', function($scope) {
$scope.name = "John Doe";
});

 ng-model creates a two-way binding between the input field and the name variable in
the controller.
 If the user changes the input value, it updates name, and the paragraph (<p>) also
updates in real-time.

3. Handling Events in the DOM with AngularJS

AngularJS allows you to handle DOM events declaratively using event-specific directives
such as ng-click, ng-change, ng-submit, etc. These directives bind DOM events to AngularJS
expressions or functions.

Prof.Bharat Vainsh, Information Technology, GEC Bhavnagar 23


Advanced Web Programming-3161611 Angular JS in Details

Common Event Handling Directives:

 ng-click: Binds a click event to an element.


 ng-submit: Binds a submit event to a form.
 ng-change: Binds a change event to an input or select element.
 ng-mouseover: Binds a mouseover event to an element.
 ng-keyup: Binds a keyup event to an input element.

Example of ng-click:

<button ng-click="greet()">Click Me</button>


<p>{{ message }}</p>

In the controller:

angular.module('myApp', [])
.controller('myCtrl', function($scope) {
$scope.greet = function() {
$scope.message = "Hello, World!";
};
});

Here, the ng-click directive binds the button’s click event to the greet() function in the
controller. When the button is clicked, the function updates the message, which is reflected in
the view due to Angular’s data binding.

4. Manipulating DOM Elements with ng-class, ng-style

AngularJS provides directives like ng-class and ng-style that dynamically manipulate the
appearance of DOM elements based on the scope values.

ng-class (Dynamically Adding/Removing Classes):


<div ng-class="{'highlight': isHighlighted}">This is a div</div>

In the controller:

angular.module('myApp', [])
.controller('myCtrl', function($scope) {
$scope.isHighlighted = true;
});

 The ng-class directive adds the highlight class to the <div> if isHighlighted is true.

ng-style (Dynamically Applying Styles):


<div ng-style="{'background-color': backgroundColor}">Styled Div</div>

In the controller:

angular.module('myApp', [])
.controller('myCtrl', function($scope) {
$scope.backgroundColor = 'blue';

Prof.Bharat Vainsh, Information Technology, GEC Bhavnagar 24


Advanced Web Programming-3161611 Angular JS in Details

});

 The ng-style directive sets the background color of the <div> to blue.

5. Directives for DOM Manipulation: ng-if, ng-show, ng-hide

AngularJS provides several directives to conditionally show or hide DOM elements.

ng-if:

This directive adds or removes elements from the DOM based on a condition.

<div ng-if="isVisible">This content is visible!</div>

If isVisible evaluates to true, the <div> is included in the DOM; otherwise, it is removed.

ng-show and ng-hide:

These directives toggle the visibility of elements based on an expression. The difference is
that ng-show keeps the element in the DOM but hides it using CSS (display: none), while ng-
hide works similarly but hides the element instead.

<div ng-show="isVisible">This is shown if true!</div>


<div ng-hide="isHidden">This is hidden if true!</div>

Summary of AngularJS DOM Manipulation Features

Feature Directive Purpose

Binds an input field to a variable in the scope


Data Binding ng-model
(two-way data binding).

Dynamic HTML Repeats an element or set of elements for


ng-repeat
Repetition each item in an array.

ng-click, ng-submit, Binds DOM events like click, submit, and


Event Handling
ng-change, etc. change to AngularJS expressions.

Conditional ng-if, ng-show, Conditionally includes or hides elements in


Rendering ng-hide the DOM based on scope values.

Class and Style Dynamically adds/removes CSS classes and


ng-class, ng-style
Manipulation applies styles based on scope values.

Visibility and CSS Toggles visibility of elements based on a


ng-show, ng-hide
Manipulation condition using CSS properties.

Prof.Bharat Vainsh, Information Technology, GEC Bhavnagar 25


Advanced Web Programming-3161611 Angular JS in Details

AngularJS Services: $http, $timeout, $interval, $window, and $log


AngularJS provides several built-in services that help you handle common tasks like making
HTTP requests, working with timeouts or intervals, interacting with the browser window, and
logging information for debugging.

Let's explore these services and how you can use them effectively.

1. $http Service

The $http service in AngularJS is used for making AJAX requests (HTTP requests) to fetch
data from a server or interact with RESTful APIs.

It provides methods for handling various types of HTTP operations such as GET, POST,
PUT, DELETE, etc.

Basic Usage of $http:

 $http returns a promise that resolves with the response when the request completes.

Example:

angular.module('myApp', [])
.controller('myCtrl', function($scope, $http) {
$http.get('https://jsonplaceholder.typicode.com/posts')
.then(function(response) {
$scope.posts = response.data; // Handle success
})
.catch(function(error) {
console.error('Error:', error); // Handle error
});
});

Here, $http.get sends a GET request to the specified URL. The .then() method handles the
success scenario, and .catch() handles any error.

 Common $http Methods:


o get(url): Sends a GET request.
o post(url, data): Sends a POST request.
o put(url, data): Sends a PUT request.
o delete(url): Sends a DELETE request.

2. $timeout Service

The $timeout service is used to execute a function after a specified delay (in milliseconds).
It’s similar to the native JavaScript setTimeout but is more AngularJS-friendly as it works
within the AngularJS digest cycle.

Basic Usage of $timeout:

Example:

Prof.Bharat Vainsh, Information Technology, GEC Bhavnagar 26


Advanced Web Programming-3161611 Angular JS in Details

angular.module('myApp', [])
.controller('myCtrl', function($scope, $timeout) {
$scope.message = "This will change after 3 seconds.";

$timeout(function() {
$scope.message = "Message changed after 3 seconds!";
}, 3000);
});

Here, $timeout changes the message after a delay of 3 seconds.

 Common Parameters for $timeout:


o Function: The function to execute after the delay.
o Delay (in ms): The time in milliseconds before the function is executed.
 $timeout also returns a promise, allowing you to chain actions after the timeout
completes.

3. $interval Service

The $interval service is similar to the native JavaScript setInterval function.

It repeatedly executes a function at specified intervals (in milliseconds). $interval


automatically works with AngularJS’s digest cycle, so you don’t need to manually trigger
updates.

Basic Usage of $interval:

Example:

angular.module('myApp', [])
.controller('myCtrl', function($scope, $interval) {
var count = 0;

var intervalPromise = $interval(function() {


count++;
$scope.counter = count;
if (count === 5) {
$interval.cancel(intervalPromise); // Stop the interval after 5 seconds
}
}, 1000); // Repeat every 1 second
});

In this example, $interval increments a counter every second. After 5 seconds, the interval is
canceled using $interval.cancel().

 Common Parameters for $interval:


o Function: The function to execute on each interval.
o Interval (in ms): The time in milliseconds between each function execution.
o $interval.cancel(promise): Cancels the interval when no longer needed.

Prof.Bharat Vainsh, Information Technology, GEC Bhavnagar 27


Advanced Web Programming-3161611 Angular JS in Details

4. $window Service

The $window service is a wrapper around the native window object in the browser.

It provides access to browser properties such as the window size, location, and history. You
can also use it to interact with the browser’s local storage or session storage.

Basic Usage of $window:

Example:

angular.module('myApp', [])
.controller('myCtrl', function($scope, $window) {
$scope.openNewWindow = function() {
$window.open('https://www.example.com', '_blank'); // Open a new window
};
});

Here, $window.open() is used to open a new browser window or tab with the specified URL.

 Common $window Methods and Properties:


o open(url, target): Opens a new browser window or tab.
o alert(message): Displays an alert dialog.
o confirm(message): Displays a confirmation dialog.
o localStorage: Accesses browser local storage for saving data across sessions.
o sessionStorage: Accesses session storage for storing data for the duration of
the page session.

5. $log Service

The $log service provides a way to log messages to the console in a standardized way. It is
used for debugging and provides additional features over the native console.log() function,
such as better formatting and the ability to use different log levels (e.g., info, warn, error).

Basic Usage of $log:

Example:

angular.module('myApp', [])
.controller('myCtrl', function($scope, $log) {
$scope.showMessage = function() {
$log.info('This is an info message.');
$log.warn('This is a warning message.');
$log.error('This is an error message.');
};
});

 Log Levels:
o $log.debug(message) — Used for debugging.
o $log.info(message) — Used for general information.
o $log.warn(message) — Used for warnings.
o $log.error(message) — Used for errors.
o

Prof.Bharat Vainsh, Information Technology, GEC Bhavnagar 28


Advanced Web Programming-3161611 Angular JS in Details

Summary of Services

Service Purpose Common Methods

For making HTTP requests to servers or


$http get(), post(), put(), delete()
APIs.

$timeout Executes a function after a specified delay. timeout(), cancel()

Executes a function repeatedly at specified


$interval interval(), cancel()
intervals.

A wrapper around the browser's window open(), alert(), localStorage,


$window
object. sessionStorage

Logs messages to the browser's console for


$log debug(), info(), warn(), error()
debugging.

Prof.Bharat Vainsh, Information Technology, GEC Bhavnagar 29


Advanced Web Programming-3161611 Angular JS in Details

AngularJS API Overview

The AngularJS API provides a comprehensive set of features for building dynamic, single-
page web applications.

The API includes a variety of modules, services, directives, and components that allow you to
create, manipulate, and manage the user interface, as well as interact with backend services
and APIs.

1. Core AngularJS Modules

AngularJS provides several key modules that are required for most applications, and they can
be extended with additional modules based on the requirements.

 ng: This is the core AngularJS module that contains the essential components for
building AngularJS applications, including directives, services, and filters.
 ngRoute: A module for handling routing and view management in single-page
applications (SPAs).
 ngAnimate: Module for adding animations to your AngularJS applications.
 ngResource: Provides a higher-level API for working with RESTful APIs.
 ngCookies: For working with cookies in AngularJS.

These modules are included when you load AngularJS, and you can include additional
modules to extend functionality (such as routing, cookies, or animations).

2. AngularJS Directives

AngularJS directives extend HTML by adding special behavior to elements. These are key
building blocks in AngularJS applications, allowing you to create dynamic interfaces.

 ng-app: Initializes an AngularJS application. It's typically placed on the root element
of the HTML document.

<html ng-app="myApp">
<body>
<div ng-controller="MyController">
<!-- Your content -->
</div>
</body>
</html>

 ng-model: Binds an HTML element (e.g., input field) to a variable in the controller,
enabling two-way data binding.

<input type="text" ng-model="name">


<p>{{ name }}</p>

 ng-repeat: Used for iterating over an array or collection to repeat an element for each
item.

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

Prof.Bharat Vainsh, Information Technology, GEC Bhavnagar 30


Advanced Web Programming-3161611 Angular JS in Details

 ng-click: Associates a click event handler with an HTML element.

<button ng-click="showMessage()">Click Me</button>

 ng-show / ng-hide: Toggles visibility of an element based on an expression.

<div ng-show="isVisible">This is visible if true</div>


<div ng-hide="isHidden">This is hidden if true</div>

3. AngularJS Services

AngularJS provides many built-in services to handle common tasks such as making HTTP
requests, managing data across views, and working with browser APIs.

Common AngularJS Services:

 $http: Used for making HTTP requests to communicate with remote servers (AJAX).

$http.get('https://api.example.com/data')
.then(function(response) {
console.log(response.data);
})
.catch(function(error) {
console.error('Error:', error);
});

 $timeout: Executes a function after a specified delay (similar to JavaScript's


setTimeout).

$timeout(function() {
console.log('This will run after 3 seconds');
}, 3000);

 $interval: Repeatedly executes a function at specified intervals (similar to


JavaScript's setInterval).

var intervalPromise = $interval(function() {


console.log('This runs every second');
}, 1000);

 $window: A wrapper around the browser’s window object for interacting with
browser features like localStorage, sessionStorage, and opening new windows.

$window.localStorage.setItem('user', 'John Doe');

 $log: Provides methods for logging messages to the browser console for debugging
purposes.

$log.info('This is an info message');


$log.warn('This is a warning message');

 $q: A promise service used for managing asynchronous operations and handling
promises more flexibly.

Prof.Bharat Vainsh, Information Technology, GEC Bhavnagar 31


Advanced Web Programming-3161611 Angular JS in Details

4. AngularJS Filters

Filters in AngularJS are used to format data before it is displayed in the view.

Filters can be applied in templates and are commonly used to transform data, format dates,
and filter arrays.

 filter: Filters an array based on a given condition.

<ul>
<li ng-repeat="item in items | filter:searchText">{{ item }}</li>
</ul>

 currency: Formats a number as a currency.

<p>{{ price | currency }}</p>

 date: Formats a date value according to a specified format.

<p>{{ birthday | date:'yyyy-MM-dd' }}</p>

 uppercase / lowercase: Transforms text to uppercase or lowercase.

<p>{{ name | uppercase }}</p>

 limitTo: Limits the number of items in an array.

<p>{{ items | limitTo:3 }}</p>

5. AngularJS Controllers
Controllers in AngularJS are JavaScript functions that control the data and behavior of your
application.

They are responsible for setting the model (data) and can interact with AngularJS services to
fetch data or perform actions.

 Controller Definition:

angular.module('myApp', [])
.controller('MyController', function($scope) {
$scope.message = "Hello, AngularJS!";
});

 Binding in the View:

<div ng-app="myApp" ng-controller="MyController">


<p>{{ message }}</p>
</div>

In this example, the message property in the controller is bound to the view using {{ message
}}.

Prof.Bharat Vainsh, Information Technology, GEC Bhavnagar 32


Advanced Web Programming-3161611 Angular JS in Details

6. AngularJS Routing (ngRoute)

The ngRoute module in AngularJS provides client-side routing, allowing you to manage
different views in a single-page application (SPA).

 Setting Up Routing:

angular.module('myApp', ['ngRoute'])
.config(function($routeProvider) {
$routeProvider
.when('/home', {
templateUrl: 'home.html',
controller: 'HomeController'
})
.when('/about', {
templateUrl: 'about.html',
controller: 'AboutController'
})
.otherwise({
redirectTo: '/home'
});
});

 Using Routes in HTML:

<div ng-app="myApp">
<a href="#!/home">Home</a>
<a href="#!/about">About</a>

<div ng-view></div> <!-- View changes based on the route -->


</div>

When you navigate to different routes, the corresponding view is injected into the ng-view
directive.

Prof.Bharat Vainsh, Information Technology, GEC Bhavnagar 33


Advanced Web Programming-3161611 Angular JS in Details

7. AngularJS Dependency Injection (DI)

AngularJS uses dependency injection to manage the dependencies of components like


controllers, services, and directives.

Dependencies are automatically provided by AngularJS, making your code more modular and
testable.

 Example of Dependency Injection:

angular.module('myApp', [])
.controller('MyController', function($scope, $http) {
$http.get('https://api.example.com/data')
.then(function(response) {
$scope.data = response.data;
});
});

In this example, $http is injected into the controller as a dependency, which allows the
controller to perform an HTTP request.

8. AngularJS Event Handling


AngularJS provides a way to handle events both at the DOM level (like ng-click) and at the
scope level (like $broadcast, $emit, $on).

 DOM Events: Handle events like clicks, mouseovers, keypresses, etc., using
AngularJS directives like ng-click, ng-mouseover, etc.

<button ng-click="showMessage()">Click Me</button>

 Scope Events: Use $emit, $broadcast, and $on for communication between
controllers and directives.

$scope.$emit('myEvent', { message: 'Hello from child' });

9. AngularJS Animation (ngAnimate)


The ngAnimate module enables animation support for AngularJS applications. You can
animate the entry, exit, and state changes of HTML elements when data changes or when
elements are added/removed.

 Basic Example (with ng-show/ng-hide):

<div ng-show="isVisible" ng-animate="'animate'">This is an animated element</div>

In the controller:

$scope.isVisible = true;

 CSS Animations: Define CSS transitions for different states like ng-enter, ng-leave,
and ng-move to animate the elements as they appear or disappear.

Prof.Bharat Vainsh, Information Technology, GEC Bhavnagar 34


Advanced Web Programming-3161611 Angular JS in Details

Steps to Create a Single-Page Website Using AngularJS

1. Set Up Your Environment

Before you start, make sure you have:

 A basic understanding of HTML, CSS, and JavaScript.


 The AngularJS library included in your project.

To get started, you can either download AngularJS or link to it directly via a CDN. Here’s
how you can link to AngularJS using a CDN:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My AngularJS SPA</title>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<link rel="stylesheet" href="style.css">
</head>
<body ng-app="myApp">
<!-- Content will go here -->
<script src="app.js"></script>
</body>
</html>

Here, we have linked the AngularJS library from the Google CDN.

2. Create an AngularJS Module and Controller

AngularJS uses modules and controllers to organize the application. A module is the main
container for the application, and a controller is used to manage the data and business logic
for a specific view.

Create a file named app.js where you will define your AngularJS application logic.

// app.js
angular.module('myApp', ['ngRoute'])
.controller('HomeController', function($scope) {
$scope.message = "Welcome to the Home Page!";
})
.controller('AboutController', function($scope) {
$scope.message = "Welcome to the About Page!";
})
.config(function($routeProvider) {
$routeProvider
.when('/home', {
templateUrl: 'home.html',
controller: 'HomeController'
})
.when('/about', {

Prof.Bharat Vainsh, Information Technology, GEC Bhavnagar 35


Advanced Web Programming-3161611 Angular JS in Details

templateUrl: 'about.html',
controller: 'AboutController'
})
.otherwise({
redirectTo: '/home'
});
});

In this code:

 ngRoute is included as a dependency to handle routing.


 We define two controllers (HomeController and AboutController) to manage the
content for the Home and About pages.
 Routing is set up using $routeProvider to map URLs to their corresponding views
and controllers.

3. Set Up Views (HTML Templates)

In a single-page application, content is dynamically loaded into the view based on the current
route. We'll create separate HTML templates for the Home and About pages.

home.html
<!-- home.html -->
<div>
<h1>{{ message }}</h1>
<p>This is the homepage content.</p>
</div>
about.html
<!-- about.html -->
<div>
<h1>{{ message }}</h1>
<p>This is the about page content.</p>
</div>

These HTML templates display a message managed by the corresponding controllers.

4. Add Navigation

You can create a simple navigation menu that allows users to switch between the different
pages (views) without reloading the entire page. In your main index.html file, add the
navigation links.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My AngularJS SPA</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.min.js"></script>

Prof.Bharat Vainsh, Information Technology, GEC Bhavnagar 36


Advanced Web Programming-3161611 Angular JS in Details

<script src="app.js"></script>
</head>
<body ng-app="myApp">
<!-- Navigation -->
<nav>
<ul>
<li><a href="#!/home">Home</a></li>
<li><a href="#!/about">About</a></li>
</ul>
</nav>

<!-- View Content -->


<div ng-view></div> <!-- This is where content will be injected based on route -->

</body>
</html>

 The ng-view directive is used to dynamically inject the content of the active route’s
template into the page.
 The a tags use Angular’s #! syntax to change routes without reloading the page.

5. Styling the Page


You can add some basic styling to make your page look nice. Create a style.css file for your
styles.

/* style.css */
body {
font-family: Arial, sans-serif;
}

nav {
background-color: #333;
color: white;
padding: 10px;
}

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

nav ul li {
display: inline;
margin-right: 10px;
}

nav ul li a {
color: white;
text-decoration: none;
}
nav ul li a:hover {
text-decoration: underline;

Prof.Bharat Vainsh, Information Technology, GEC Bhavnagar 37


Advanced Web Programming-3161611 Angular JS in Details

h1 {
color: #333;
}
This basic CSS adds styles to the navigation menu and headings.

6. Testing Your Application


Once you have set up the HTML, AngularJS, and routing, your single-page website is ready
to go. When you open index.html in the browser, you should see the navigation bar.

Clicking on "Home" or "About" should dynamically load the corresponding page content
without reloading the whole page.

Final Folder Structure:


/my-angularjs-app
/index.html
/home.html
/about.html
/app.js
/style.css

7. Enhancements and Features to Add

You can enhance your AngularJS single-page website by adding more features:

 Form Handling: Use AngularJS forms with validation to capture user input.
 Service Integration: Fetch data from a RESTful API using the $http service and
display it in your views.
 Dynamic Content: Bind dynamic content using AngularJS's two-way data binding
and filters.
 Animations: Add animations to page transitions and element visibility using the
ngAnimate module.

Conclusion

Creating a single-page website with AngularJS is straightforward and requires understanding


the key concepts of modules, controllers, routing, and templates. By combining these tools,
you can create dynamic web applications that provide a rich, interactive user experience
without full-page reloads.

Here’s a summary of what we’ve covered:

 Setting up an AngularJS application and including necessary libraries.


 Using routing to load different views based on URL.
 Creating controllers to manage data and inject it into views.
 Setting up basic navigation with AngularJS’s routing system (ngRoute).

Prof.Bharat Vainsh, Information Technology, GEC Bhavnagar 38


Advanced Web Programming-3161611 Angular JS in Details

Example: 1 Weather Information System by using API

Index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Weather App with AngularJS</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-app="weatherApp">

<div ng-controller="WeatherCtrl">
<h1>Weather in {{ cityName }}</h1>
<form ng-submit="getWeather()">
<input type="text" ng-model="city" placeholder="Enter city" required>
<button type="submit">Get Weather</button>
</form>

<div ng-if="weather">
<h2>{{ weather.name }} - {{ weather.weather[0].description }}</h2>
<p>Temperature: {{ weather.main.temp }}°C</p>
<p>Humidity: {{ weather.main.humidity }}%</p>
<p>Wind Speed: {{ weather.wind.speed }} m/s</p>
</div>

<div ng-if="errorMessage">
<p>{{ errorMessage }}</p>
</div>
</div>
</body>
</html>

Prof.Bharat Vainsh, Information Technology, GEC Bhavnagar 39


Advanced Web Programming-3161611 Angular JS in Details

app.js

var app = angular.module('weatherApp', []);


app.controller('WeatherCtrl', function($scope, $http) {
$scope.city = "";
$scope.cityName = "Enter a city to get the weather";

$scope.getWeather = function() {
if (!$scope.city) {
$scope.errorMessage = "Please enter a city name.";
$scope.weather = null;
return;
}
var apiKey = 'YOUR_OPENWEATHERMAP_API_KEY';
var url =
`https://api.openweathermap.org/data/2.5/weather?q=${$scope.city}&appid=${apiKey}&uni
ts=metric`;
$http.get(url)
.then(function(response) {
$scope.weather = response.data;
$scope.cityName = $scope.weather.name;
$scope.errorMessage = null;
}, function(error) {
$scope.weather = null;
$scope.errorMessage = "City not found. Please try again.";
});
};
});

Prof.Bharat Vainsh, Information Technology, GEC Bhavnagar 40


Advanced Web Programming-3161611 Angular JS in Details

References
Faculty Guide: Prof. Bharat Vainsh, Information Technology, GEC Bhavnagar

Textbooks (Best for beginners to foundational learning):

1. "HTML and CSS: Design and Build Websites" by Jon Duckett


2. "JavaScript and JQuery: Interactive Front-End Web Development" by Jon Duckett
3. "Learning Web Design" by Jennifer Niederst Robbins
4. Web Technologies Black Book HTML, JavaScript, PHP, Java, JSP, ASP.NET, XML, and
AJAX.

Reference Books (Best for in-depth information on specific technologies):

5. "JavaScript: The Definitive Guide" by David Flanagan


6. "CSS: The Definitive Guide" by Eric A. Meyer
7. AngularJS Essentials by Rodrigo Branas
8. Angularjs in Action ISBN 9789351198383 Ruebbelke, Wiley Publication
9. Node.js in Action ISBN 9789386052049 Alex Young, Bradley Meck, Mike
10. Node.Js in Practice ISBN 9789351197744 Alex Young, Marc Harter, Ben Noordhuis
Wiley Publication

Technical Books (Best for advanced, specialized knowledge and best practices):

11. "Designing with Web Standards" by Jeffrey Zeldman


12. "Node.js Design Patterns" by Mario Casciaro
13. "You Don’t Know JS (Book Series)" by Kyle Simpson
14. "Pro Git" by Scott Chacon and Ben Straub

• Website:

1. https://www.bharatvainsh.in/
2. https://smarteportal.blogspot.com/
3. https://www.w3schools.com/
4. https://www.javatpoint.com/
5. https://www.studentstutorial.com/
6. https://www.tutorialspoint.com/seo/index.htm
7. https://javascript.info/
8. https://www.guru99.com/
9. https://www.tutorialspoint.com/php/
10. https://www.codecademy.com/catalog/subject/web-development
11. https://www.geeksforgeeks.org/
12. https://www.studentstutorial.com/
13. https://www.freecodecamp.org
14. https://www.w3schools.com/angular/
15. https://devfreebooks.github.io/
16. https://www.javatpoint.com/nodejs-tutorial
17. https://nodejs.org/en/download/

Prof.Bharat Vainsh, Information Technology, GEC Bhavnagar 41

You might also like