BEIT 6 Introduction To AngularJS ClassNotes Unit 2 BharatVainsh IT GECBVN
BEIT 6 Introduction To AngularJS ClassNotes Unit 2 BharatVainsh IT GECBVN
Unit-2-Introduction to AngularJS
What is AngularJS.
AngularJS is an open-source front-end web application framework developed by Google. It is
designed to facilitate the development of dynamic, single-page applications (SPAs) by
extending HTML with additional features.
8. Testing:
o AngularJS was designed with testability in mind, making it easier to write
unit tests for your application.
Advantages of AngularJS
1. Faster Development:
o With features like two-way data binding, directives, and built-in services,
AngularJS reduces the amount of code developers need to write, speeding up
the development process.
2. Modular Architecture:
o AngularJS promotes modularity in code through components like controllers,
services, directives, and filters, making the application easier to maintain and
extend.
3. Improved Testing:
o AngularJS is designed with testability in mind. It provides tools to easily test
components like controllers, services, and directives.
4. Reusability:
o With services and directives, AngularJS promotes code reusability. You can
create modular and reusable code blocks that can be shared across multiple
parts of the application.
5. Single Page Applications (SPA):
o AngularJS enables building SPAs, where the application loads once and
dynamically updates without requiring full-page reloads, resulting in faster
and smoother user experiences.
6. Two-Way Data Binding:
o Reduces the need for writing complex code to sync data between the model
and view. It automatically handles updates, improving code efficiency and
readability.
7. Community and Support:
o AngularJS, being backed by Google, has a large and active community, plenty
of resources, and strong support, making it easier for developers to get help
and stay up to date with the latest trends.
Disadvantages of AngularJS
1. Complexity: The learning curve can be steep, especially for developers new to
JavaScript frameworks. Concepts like dependency injection and the MVC architecture
may take time to master.
5. Limited Flexibility: The framework imposes certain structures and patterns, which
can be restrictive for developers looking for a more flexible approach.
The Model
The model is responsible for managing application data. It responds to the request from view
and to the instructions from controller to update itself.
The View
The Controller
The controller responds to user input and performs interactions on the data model objects.
The controller receives input, validates it, and then performs business operations that modify
the state of the data model.
A Single Page Application (SPA) in AngularJS is a web application that loads a single
HTML page and dynamically updates that page as the user interacts with the app. This
approach contrasts with traditional multi-page applications, where each user interaction
typically results in a full page reload.
Dynamic Content Loading: SPAs load content dynamically without refreshing the entire
page. AngularJS uses AJAX (Asynchronous JavaScript and XML) requests to fetch data from
the server and update the view accordingly.
Routing: AngularJS provides a routing module (ngRoute) that allows developers to define
routes in the application. Each route corresponds to a different view or component, enabling
seamless navigation without full page reloads.
Two-Way Data Binding: AngularJS's two-way data binding keeps the model and the view in
sync. Any changes made to the model update the view and vice versa, providing a smooth
user experience.
Components and Directives: AngularJS supports the creation of reusable components and
directives, which help manage the application's structure and behavior, making it easier to
build and maintain complex UIs.
Performance: By avoiding full page reloads, SPAs can provide a faster and more fluid user
experience
SEO Challenges: Traditional SPAs can face challenges with search engine optimization
(SEO) because they rely heavily on JavaScript to render content. However, techniques like
server-side rendering (SSR) or pre-rendering can help mitigate these issues.
1. Modules:
o An AngularJS application is organized into modules, which are containers for
the various components like controllers, services, and directives.
o A module can be thought of as an "app" that brings together everything
needed to run the application.
2. Controllers:
o Controllers in AngularJS are used to define the application logic and manage
the data that is passed between the view and the model.
o Controllers are responsible for handling user input and making decisions based
on the application’s state.
app.controller('MainController', function($scope) {
$scope.message = 'Hello, AngularJS!';
});
3. Scope:
oThe $scope object is a fundamental part of AngularJS and acts as a bridge
between the controller and the view.
o Any data added to the $scope object in a controller becomes available in the
view.
4. Expressions:
o AngularJS uses expressions to display dynamic content. Expressions are
written inside double curly braces {{ expression }}.
5. Directives:
o AngularJS uses directives to extend HTML and add behavior to the DOM
elements.
o Some common built-in directives are ng-app, ng-model, ng-repeat, and ng-
click.
6. Services:
o Services are used to share data and logic between controllers and other
components.
o You can use built-in services like $http for making API calls, $timeout for
scheduling tasks, or create your own custom services.
app.service('UserService', function() {
this.getUser = function() {
return { name: 'John Doe' };
};
});
ng-binding:
It’s not often used explicitly anymore, as Angular provides more straightforward data binding
with {{expression }} syntax.
How it works:
You apply ng-binding to an HTML element, and it will automatically update the
content of that element whenever the value of the model (the associated Angular
variable) changes.
Example:
<span ng-binding="message"></span>
Here, the content of the <span> will be automatically updated whenever the message
variable in the controller (model) changes.
AngularJS provides two-way data binding, which means changes in the view automatically
update the model, and changes in the model automatically update the view.
Syntax:
<input ng-model="name">
<p>Hello, {{ name }}!</p>
2. Expression in AngularJS
An expression in AngularJS is any valid JavaScript code enclosed within curly braces {{ }}.
This is the simplest form of binding and is used to display the value of a model or a
calculation result directly in the view.
How it works:
The expression evaluates the JavaScript code inside the {{}}, and AngularJS
automatically updates the DOM whenever the value changes.
Example:
<p>{{ message }}</p>
In this example, the value of message is displayed in the <p> tag, and if message
changes, the view updates automatically.
<div ng-controller="appController">
<span>
4+5 = {{4+5}}
</span>
<br />
<br />
<span ng-init="quantity=5; cost=25">
Total Cost = {{quantity * cost}}
</span>
</div>
Using numbers
<p>Expense on Books: {{cost * quantity}} Rs</p>
Using Strings
<p>Hello {{student.firstname + " " + student.lastname}}!</p>
Using Object
<p>Roll No: {{student.rollno}}</p>
Using Array
<p>Marks (Math): {{marks[3]}}</p>
Key Differences:
ng-binding is a directive used to bind an element's content to a model, and it’s not as
commonly used today as {{}} expressions.
Expression is a template expression that directly binds data or performs calculations
inside the {{ }} syntax.
Directives in AngularJS
A directive is a special marker in AngularJS that attaches behaviour to elements in the DOM
(Document Object Model). Directives can either extend HTML by adding new attributes or
custom tags, or they can be used to manipulate the DOM (e.g., show/hide elements, repeat
elements, etc.).
1. ng-app
o Initializes the AngularJS application.
<html ng-app="myApp">
2. ng-controller
o Defines the controller that will manage the scope for a part of the HTML
view.
<div ng-controller="MainController">
<p>{{ message }}</p>
</div>
3. ng-model
o Binds the value of an HTML form element (like an <input>) to a variable in
the controller.
<input ng-model="name">
<p>Hello, {{ name }}!</p>
4. ng-repeat
o Loops through an array and repeats HTML for each item in the array.
<ul>
<li ng-repeat="item in items">{{ item }}</li>
</ul>
5. ng-click
o Executes a function when an element is clicked.
AngularJS allows you to create custom directives for specific behavior that you want to reuse
across different parts of your application.
<hello-world></hello-world>
This would display:
Hello, World!
Explanation:
restrict: Determines how the directive can be used in HTML (as an element, attribute,
class, or comment).
template: Defines the HTML to be injected wherever the directive is used.
Modules
In AngularJS, an application is defined as a module, which acts as a container for the various
components like controllers, services, directives, etc.
Syntax:
Controllers
Controllers in AngularJS are responsible for adding behaviour to the application. They handle
the data and functions that are passed to the view (HTML).
Syntax:
app.controller('MyController', function($scope) {
$scope.message = 'Hello, AngularJS!';
});
o $scope binds the data between the controller and the view.
$scope
The $scope is a special JavaScript object. Both View and controller have access to the scope
object. It can be used for communication between view and controller. Scope object contains
both data and functions.
Every AngularJS application has a $rootScope that is the topmost scope created on the DOM
element which contains the ng-app directive. It can watch expressions and propagate events.
Filters
Filters are used to format data before it's displayed in the view. They can be applied within
expressions to modify the output (e.g., formatting dates, currency).
Common Filters:
o currency: Formats a number as currency.
o date: Formats a date.
o lowercase / uppercase: Converts text to lowercase or uppercase.
Example:
Routing
Routing in AngularJS allows you to build Single Page Applications (SPA), where different
views (or pages) are displayed without reloading the entire web page. Instead, the content of
the page is dynamically updated based on the URL, creating a smoother and faster user
experience.
AngularJS provides a built-in service called $route and a module called ngRoute to help
handle routing in the application.
Define multiple views for your application (e.g., home, about, contact).
Map specific URLs to views and controllers.
Dynamically change views based on the user’s interaction or the URL path.
1. Include ngRoute Module: First, you need to include the ngRoute module, which is a
part of AngularJS but is not included by default.
2. Define Routes: You define the routes in the config function of your AngularJS
module using the $routeProvider.
3. Create Views and Controllers: You create different views (templates) and assign
controllers to them.
To use routing in AngularJS, you must first include the ngRoute module. This can be done by
adding a script tag to include the angular-route.js file.
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular-route.js"></script>
Then, you need to inject the ngRoute module as a dependency into your AngularJS
application.
Once you have added ngRoute and configured your module, you can set up routes using
$routeProvider inside the .config() block.
Define Routes: In the route configuration, you map a URL path to a view (HTML
template) and a controller.
app.config(function($routeProvider) {
$routeProvider
.when('/home', {
templateUrl: 'home.html',
controller: 'HomeController'
})
.when('/about', {
templateUrl: 'about.html',
controller: 'AboutController'
})
.otherwise({
redirectTo: '/home' // Default route if the path doesn't match
}); });
when(): Defines a route by specifying the URL (/home or /about), the template to
load (home.html or about.html), and the controller to use (HomeController or
AboutController).
otherwise(): Redirects to a default route when the URL doesn't match any defined
routes.
Each route is associated with a view (template) and a controller. You create these templates
as separate HTML files or inline templates.
<div>
<h2>Welcome to the Home Page</h2>
<p>This is the homepage of the application. </p>
</div>
<div>
<h2>About Us</h2>
<p>This is the about page of the application. </p>
</div>
app.controller('HomeController', function($scope) {
$scope.message = "This is the home page";
});
app.controller('AboutController', function($scope) {
$scope.message = "This is the about page";
});
To display the content associated with the active route, you need to include the <ng-
view></ng-view> directive in the HTML. This is where AngularJS will insert the
corresponding view (template) for the active route.
<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="UTF-8">
<title>AngularJS Routing</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular-
route.js"></script>
<script src="app.js"></script>
</head>
<body>
<div>
<a href="#/home">Home</a> |
<a href="#/about">About</a>
</div>
The links (<a href="#/home"> and <a href="#/about">) allow the user to navigate
between views.
The ng-view directive is the placeholder where the corresponding templates will be
inserted when a route is activated.
HTML:
<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="UTF-8">
<title>AngularJS Routing Example</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular-
route.js"></script>
<script src="app.js"></script>
</head>
<body>
<div>
<a href="#/home">Home</a> |
<a href="#/about">About</a>
</div>
</body>
</html>
app.js:
var app = angular.module('myApp', ['ngRoute']);
app.config(function($routeProvider) {
$routeProvider
.when('/home', {
templateUrl: 'home.html',
controller: 'HomeController'
})
.when('/about', {
templateUrl: 'about.html',
controller: 'AboutController'
})
.otherwise({
redirectTo: '/home'
});
});
app.controller('HomeController', function($scope) {
$scope.message = "Welcome to the Home Page!";
});
app.controller('AboutController', function($scope) {
$scope.message = "Learn more about us on the About Page!";
});
home.html:
<div>
<h2>{{ message }}</h2>
<p>This is the home page content.</p>
</div>
about.html:
<div>
<h2>{{ message }}</h2>
<p>This is the about page content.</p>
</div>
You can also pass parameters in the URL and retrieve them inside the controller.
app.config(function($routeProvider) {
$routeProvider
.when('/user/:id', {
templateUrl: 'user.html',
controller: 'UserController'
});
});
URL:
$routeParams allows you to access the parameters defined in the route (:id).
Template (user.html):
html
<div>
<h2>User Profile</h2>
<p>User ID: {{ userId }}</p>
</div>
When the user navigates to #/user/123, the controller will display User ID: 123.
You can handle cases where the user tries to access an undefined route by setting up a
fallback route using the. otherwise() method.
$routeProvider
. otherwise({
redirectTo: '/home'
});
Services
Services in AngularJS are reusable business logic components that can be injected into
controllers or other services.
They are used to share data and functions between different parts of the application.
Syntax:
app.service('UserService', function() {
this.getUser = function() {
return { name: 'John Doe' };
};
});
AngularJS internally provides many services that we can use in our application. $http is one
example. There are other useful services, such as $route, $window, $location and so on.
Some of the commonly used services in any AngularJS applications are listed below.
/myApp
/app
/controllers
- mainController.js
/services
- userService.js
/views
- index.html
/assets
- css
- js
- index.html
index.html: The main entry point of the application where AngularJS is bootstrapped
using ng-app and where the app's view is loaded.
controllers/: Contains all the AngularJS controllers responsible for managing the
app's logic and data.
services/: Contains the services used to share data or handle API calls.
views/: Contains the HTML templates used by AngularJS to display the content.
assets/: Contains static files such as CSS and JS.
<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="UTF-8">
<title>AngularJS 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>
<input type="text" ng-model="name" placeholder="Enter your name">
<p>Hello, {{ name }}!</p>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('MainController', function($scope) {
$scope.message = 'Welcome to AngularJS!';
$scope.name = '';
});
</script>
</body>
</html>
In this example:
Explanation:
1. ng-app="myapp": This tells AngularJS that this HTML page is part of the myapp
AngularJS application.
2. ng-controller="mycrl": The mycrl controller is assigned to this part of the HTML,
which allows access to the $scope object (where the message variable is stored).
3. {{ message }}: This is AngularJS's data binding. It binds the message variable from
the $scope to the HTML content.
4. ng-click="show()": This binds the button to the show function. When the button is
clicked, it will execute the show() function, which updates the message to
"Welcome".
Download the Library: You can either download the minified or unminified version of AngularJS.
Click on the version you want to download, which will prompt a download of a .js file (e.g., angular.js
or angular.min.js).
Html(index.html)
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<title>My AngularJS App</title>
<script src="angular.js"></script> <!-- or angular.min.js for production -->
<script src="app.js"></script>
</head>
<body>
<div ng-controller="MainController">
<h1>{{ message }}</h1>
</div>
</body>
</html>
Create an app.js File: In the same directory, create a file named app.js with the following content:
Javascript(app.js)
cd C:\my-angular-app
Start the Server: Run the following command:
http-server
Open Your Browser: Go to http://localhost:8080 to see your AngularJS application.
1. AngularJS Library/Framework(frontend)
https://angularjs.org/
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
https://react.dev/
2. Editor/IDE
https://code.visualstudio.com/docs/nodejs/angular-tutorial
https://www.jetbrains.com/webstorm/
https://github.blog/news-insights/product-news/sunsetting-atom/
https://www.sublimetext.com/
https://notepad-plus-plus.org/
https://developer.apple.com/xcode/(for apple platform)
https://netbeans.apache.org/front/main/index.html
https://brackets.io/
Online
https://onecompiler.com/
https://www.programiz.com/python-programming/online-compiler/
3. Web Browser
https://www.google.com/chrome/
https://www.mozilla.org/en-US/firefox/windows/
https://www.opera.com/
https://www.microsoft.com/en-us/edge/download
5.MongoDB
https://www.mongodb.com/try/download/community
https://www.bharatvainsh.in/
https://smarteportal.blogspot.com/
Background
Comparison Between 200 and 400
Status
Meaning Description Example
Code
The request was successfully processed
Accessing a webpage or
200 OK Success and the server returned the requested
API endpoint successfully.
data.
The server could not understand the
400 Bad Client Invalid parameters in a
request due to malformed syntax or
Request Error URL or API request.
invalid data.
Key Differences
Cache Uses cached resources unless Can bypass the cache (hard reload) or use
Behavior manually forced cached resources (soft reload)
Common For minor updates or re-rendering For clearing cache issues or ensuring you
Use the page see the latest content
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/