BEIT 6 Angular JS in Details ClassNotes Unit 3 Bha - 250210 - 133356
BEIT 6 Angular JS in Details ClassNotes Unit 3 Bha - 250210 - 133356
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:
Module Example
app.controller('MainController', function($scope) {
});
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).
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).
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.
<!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', []);
</body>
</html>
Explanation:
• The controller MainController is associated with the HTML view using ng-
controller="MainController".
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).
<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.
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.
<!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>
<script>
var app = angular.module('myApp', []);
app.controller('MainController', function() {
var vm = this; // Use "this" to reference the controller
vm.changeMessage = function() {
vm.message = "You clicked the button!";
};
});
</script>
</body>
</html>
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).
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.
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.
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.
AngularJS comes with a variety of built-in filters for formatting and transforming data:
1. currency
You can customize the currency symbol and the number of decimal places:
2. date
3. filter
<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.
4. json
<ul>
<li ng-repeat="item in items | limitTo:2">{{ item }}</li>
</ul>
<!-- Output: only the first 2 items from the array -->
Example (string):
6. lowercase
8. number
Purpose: Formats a number with commas and a specified number of decimal places.
Syntax: {{ expression | number : fractionSize }}
Example:
9. orderBy
<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>
Filters can also be used programmatically in the controller. You can use $filter to apply
filters to data.
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.
In AngularJS, forms are created using standard HTML <form> tags, but AngularJS adds
directives to handle data binding, validation, and other functionalities.
Example:
<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>
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.
1. Built-in Validators
Angular provides several built-in validators like required, minlength, maxlength, pattern, etc.
Example:
<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>
2. Form State
AngularJS provides a variety of properties for tracking the form's state, such as $valid,
$invalid, $dirty, $pristine, and $submitted.
Sometimes, you may need to create your own custom validation logic. AngularJS allows you
to define custom validators to check specific conditions.
You can create a custom validator by adding a function to the $validators object in
AngularJS.
app.controller('FormController', function($scope) {
$scope.checkAge = function(age) {
return age >= 18; // Validate that age is at least 18
};
});
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.
You can create a custom asynchronous validator using $http to check the availability of a
username:
});
Usage in HTML:
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>
Here:
Summary
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.
Services in AngularJS are singleton objects that are used to share data and logic across the
application. They can be used to:
They help separate concerns, making your code more modular, testable, and maintainable.
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.
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;
};
});
Usage in Controller:
In the HTML:
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;
};
In this case, myFactory is a factory that returns an object with a getMessage() method.
Usage in Controller:
In the HTML:
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.
app.config(function(myProvider) {
myProvider.setMessage("Hello from Provider!");
});
In the HTML:
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:
This service makes an HTTP GET request and returns the response as a promise, which can
then be handled in the controller.
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;
};
});
In one controller:
In another controller:
This allows different controllers to share and update user information without direct
dependency between them.
Service Methods: Services typically expose methods that can be used to encapsulate logic.
These methods can be called by the controllers or other components.
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.
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.
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.
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);
};
$scope.submitForm = function() {
alert('Form submitted with name: ' + $scope.formData.name);
};
});
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.
$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.
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>
</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.
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.
angular.module('myApp', [])
.controller('myCtrl', function($scope, $timeout) {
$scope.triggerCustomEvent = function() {
// Custom event trigger
$scope.$broadcast('customEvent', { message: 'This is a custom event!' });
};
$timeout(function() {
$scope.triggerCustomEvent();
}, 3000); // Trigger custom event after 3 seconds
});
In HTML:
In this example:
AngularJS has several built-in events that you can use in your application for handling
specific scenarios.
angular.module('myApp', [])
.run(function($rootScope) {
$rootScope.$on('$routeChangeStart', function(event, next, current) {
console.log('Route is changing...');
});
});
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.
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.
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:
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.
<ul>
<li ng-repeat="item in items">{{ item }}</li>
</ul>
Here, ng-repeat repeats the <li> element for each item in the items array.
The element will only be included in the DOM if the isVisible condition evaluates to true.
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.
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.
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.
Example of ng-click:
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.
AngularJS provides directives like ng-class and ng-style that dynamically manipulate the
appearance of DOM elements based on the scope values.
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.
In the controller:
angular.module('myApp', [])
.controller('myCtrl', function($scope) {
$scope.backgroundColor = 'blue';
});
The ng-style directive sets the background color of the <div> to blue.
ng-if:
This directive adds or removes elements from the DOM based on a condition.
If isVisible evaluates to true, the <div> is included in the DOM; otherwise, it is removed.
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.
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.
$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.
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.
Example:
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);
});
3. $interval Service
Example:
angular.module('myApp', [])
.controller('myCtrl', function($scope, $interval) {
var count = 0;
In this example, $interval increments a counter every second. After 5 seconds, the interval is
canceled using $interval.cancel().
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.
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.
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).
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
Summary of Services
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.
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.
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>
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.
$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(function() {
console.log('This will run after 3 seconds');
}, 3000);
$window: A wrapper around the browser’s window object for interacting with
browser features like localStorage, sessionStorage, and opening new windows.
$log: Provides methods for logging messages to the browser console for debugging
purposes.
$q: A promise service used for managing asynchronous operations and handling
promises more flexibly.
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.
<ul>
<li ng-repeat="item in items | filter:searchText">{{ item }}</li>
</ul>
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!";
});
In this example, the message property in the controller is bound to the view using {{ message
}}.
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'
});
});
<div ng-app="myApp">
<a href="#!/home">Home</a>
<a href="#!/about">About</a>
When you navigate to different routes, the corresponding view is injected into the ng-view
directive.
Dependencies are automatically provided by AngularJS, making your code more modular and
testable.
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.
DOM Events: Handle events like clicks, mouseovers, keypresses, etc., using
AngularJS directives like ng-click, ng-mouseover, etc.
Scope Events: Use $emit, $broadcast, and $on for communication between
controllers and directives.
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.
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.
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', {
templateUrl: 'about.html',
controller: 'AboutController'
})
.otherwise({
redirectTo: '/home'
});
});
In this code:
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>
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>
<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>
</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.
/* 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;
h1 {
color: #333;
}
This basic CSS adds styles to the navigation menu and headings.
Clicking on "Home" or "About" should dynamically load the corresponding page content
without reloading the whole page.
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
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>
app.js
$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.";
});
};
});
References
Faculty Guide: Prof. Bharat Vainsh, Information Technology, GEC Bhavnagar
Technical Books (Best for advanced, specialized knowledge and best practices):
• 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/