0% found this document useful (0 votes)
13 views

AngularJS Notes

AngularJS is a client-side JavaScript MVC framework designed for developing dynamic web applications, providing features like data binding, custom directives, and dependency injection. It allows for the creation of Single Page Applications and is open-source, making it accessible to developers worldwide. While it offers advantages such as reusable components and cross-browser compatibility, it also has disadvantages like security concerns and lack of degradation.

Uploaded by

havahix348
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)
13 views

AngularJS Notes

AngularJS is a client-side JavaScript MVC framework designed for developing dynamic web applications, providing features like data binding, custom directives, and dependency injection. It allows for the creation of Single Page Applications and is open-source, making it accessible to developers worldwide. While it offers advantages such as reusable components and cross-browser compatibility, it also has disadvantages like security concerns and lack of degradation.

Uploaded by

havahix348
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/ 55

AngularJS

By: Asst. Professor Sonu Kumavat


Dept.: Information Technology
Topics

1. Overview of AngularJS, Need of AngularJS in real web sites


2. AngularJS modules
3. AngularJS built-in directives, custom directives
4. AngularJS expressions, JS Data Binding
5. AngularJS filters, controllers, scope
6. AngularJS dependency injection,
7. AngularJS Services, Form Validation,
8. Routing using ng-Route, ng-Repeat, ng-style, ng-view,
9. Built-in Helper Functions, Using Angular JS with Typescript
Overview of AngularJS
● AngularJS is a client side JavaScript MVC framework to develop a dynamic web
application,
● AngularJS was originally started as a project in Google but now, it is open source
framework.
● AngularJS is entirely based on HTML and JavaScript.
● AngularJS is also called just "Angular".
● AngularJS changes static HTML to dynamic HTML.
● It extends the ability of HTML by adding built-in attributes and components and
also provides an ability to create custom attributes using simple JavaScript.
● AngularJS can be used to create Single Page Applications.
Features
● AngularJS is an efficient framework that can create Rich Internet Applications
(RIA).
● AngularJS provides developers an options to write client side applications using
JavaScript in a clean Model View Controller (MVC) way.
● Applications written in Angular JS are cross-browser compliant.
● AngularJS automatically handles JavaScript code suitable for each browser.
● Open source, completely free, and used by thousands of developers around the
world. It is licensed under the Apache license version 2.0.
● It is a framework to build large scale, high-performance, and easy-to-maintain
web applications.
Core Features
1. Data-binding
2. Scope
3. Controller
4. Services
5. Filters
6. Directives
7. Templates
8. Routing
9. Model view whatever
10. Deep Linking
11. Dependency Injection
Advantages
1. It provides the capability to create Single Page Application.
2. It provides data binding capability to HTML.
3. AngularJS code is unit testable.
4. AngularJS uses dependency injection and make use of separation of concerns.
5. AngularJS provides reusable components.
6. Developers can achieve more functionality with short code.
7. In AngularJS, views are pure html pages, and controllers written in JavaScript do the
business processing.
8. AngularJS applications can run on all major browsers and smart phones, including
Android and iOS based phones/tablets.
Disadvantages

1. Not Secure
2. Not Degradable
AngularJS MVC Architecture

● MVC stands for Model View Controller.


● It is a software design pattern for developing
web applications.
● It is very popular because it isolates the
application logic from the user interface layer
and supports separation of concerns.
AngularJS MVC Architecture

1. Model: It is responsible for managing application data. It responds to the


requests from view and to the instructions from controller to update itself.
2. View: It is responsible for displaying all data or only a portion of data to the
users. It also specifies the data in a particular format triggered by the
controller's decision to present the data.
3. Controller: It is responsible to control the relation between models and
views. The controller receives input, validates it, and then performs business
operations that modify the state of the data model.
Need of AngularJS in Real Websites

1. More community
2. Readable code
3. Google as creation
4. Customizable
5. Flexible
6. Fast for small
7. Charge dependency
8. Pre-made solutions
9. Easy testing
AngularJS Modules

● A module in AngularJS is a container of the different parts of an application


such as controller, service, filters, directives, factories etc.
● It supports separation of concern using modules.
● Modules are used to separate logic such as services, controllers, application
etc. from the code and maintain the code clean.
● We define modules in separate js files.
● Controllers always belong to a module.
● A module is used as a Main() method.
Creating a Module
var app = angular.module("Module-name", []);

Example:

<div ng-app="myApp">...</div>

<script>

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

</script>
Adding a Controller
Add a controller to your application, and refer to the controller with the ng-controller
directive:

app.controller("Controller-name", function($scope)
{
$scope.variable-name= "";
});
Adding a Controller
<div ng-app="myApp" ng-controller="myCtrl">
{{ firstName + " " + lastName }}
</div>
<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
});
</script>
AngularJS Directives

● AngularJS facilitates you to extend HTML with new attributes. These


attributes are called directives.
● There is a set of built-in directive in AngularJS which offers functionality to
your applications. You can also define your own directives.
● Directives in AngularJS are starting with ng- where ng stands for Angular
AngularJS Directives

● ng-app: Auto bootstrap AngularJS Application.


● ng-init: initializes AngularJS variables.
● ng-model: binds HTML control’s value to a property on the $scope object.
● ng-repeat: repeats html elements for each item in a collection.
● ng-controller: Attaches the controller of MVC to the view.
● ng-bind: replaces the value of HTML control with the value of specified
AngularJS expressions.
AngularJS Directives

● ng-show: Display HTML element based on the value of specified


expression.
● ng-readonly: makes HTML element read-only based on the value of
specified expression.
● ng-disabled: sets the disable attributes on the HTML element if specified
expression evaluates to true.
● ng-if: removes or recreates HTML element based on expression.
● ng-click: specifies custom behaviour when an element is clicked.
AngularJS Custom Directives

● Custom directives are used in AngularJS to extend the functionality of


HTML.
● Custom directives are defined using “directive” function.
● It simply replaces the element for which it is activated.
● angularJS application during bootstrap finds the matching element and do
one time activity using its compile() method of the custom directive then
process the element using link() method of the custom directive based on the
scope of the directive
AngularJS Custom Directives

AngularJS provides support to create custom directives for the following type of
elements.
1. Element directives: activates when a matching element is encountered.
2. Attribute: activates when a matching attribute is encountered.
3. CSS: activates when a matching css style is encountered.
4. Comment: activates when a matching comment is encountered.
AngularJS Expressions
● AngularJS expression is like JavaScript expression surrounded with braces-
{{expression}}.
● Expressions are used to bind application data to HTML.
● AngularJS evaluates the specified expression and binds the result data to HTML.
● It can contain literals, operators and variable like JavaScript expression.
● For example: an expression {{2/2}} will produce the result 1 and will be bound to
HTML.
● {{ 5 + 5 }} or {{ firstName + " " + lastName }}
AngularJS Data Binding

● Data binding is a very useful and powerful feature used in software


development technologies.
● It acts as a bridge between the view and business logic of the application.
● AngularJS follows Two-Way data binding model.
One-Way Data Binding
1. The one-way data binding is an approach
where a value is taken from the data
model and inserted into an HTML
element.
2. There is no way to update model from
view.
3. It is used in classical template systems.
4. These systems bind data in only one
direction.
Two-Way Data Binding
1. Data-binding in Angular apps is the
automatic synchronization of data between
the model and view components.
2. Data binding lets you treat the model as the
single-source-of-truth in your application.
3. The view is a projection of the model at all
times. If the model is changed, the view
reflects the change and vice versa.
Example
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="" ng-init="firstName='Ajeet'">
<p>Input something in the input box:</p>
<p>Name: <input type="text" ng-model="firstName"></p>
<p>You wrote: {{ firstName }}</p>
</div>
</body>
</html>
Output
Example where two text fields are bound together with two
ng-model directives
<!DOCTYPE html>
<html>
<script
src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div data-ng-app="" data-ng-init="quantity=1;price=20">
<h2>Cost Calculator</h2>
Quantity: <input type="number" ng-model="quantity">
Price: <input type="number" ng-model="price">
<p><b>Total in rupees:</b> {{quantity * price}}</p>
</div>
</body>
</html>
Output
AngularJS Filters
● Filters can be added in AngularJS to format data.
● There are some filters that are added in the AngularJS for the sake of making the
formatting and working with data easier.
● There are several in-built filters in AngularJS. They are listed here along with some
examples to make the understanding easier.
● Filters are generally added to the expressions by using the pipe (|) character.
● For example, the filter {{ fullName | uppercase }} formats the fullName into the
uppercase format.
AngularJS Filters
Some of the pre-built filters in AngularJS are:
1. currency The number is formatted to currency format.
2. date The date is specified to a specific format.
3. filter The array is filtered on the basis of the provided criteria.
4. limitTo The array or an string is limited into a specified number of elements/characters.
5. number A number if formatted to a string.
6. orderBy The array is ordered by an expression.
7. lowercase This filter converts a string to lowercase letters.
8. uppercase This filter converts a string to uppercase letters.
9. json It converts a JavaScript object into a JSON string.
Adding Filters to Expressions
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="personCtrl">
<p>The name is {{ lastName | uppercase }}</p>
</div>
<script>
angular.module('myApp', []).controller('personCtrl', function($scope) {
$scope.firstName = "John",
$scope.lastName = "Doe"
});
</script>

</body>
</html>
<!DOCTYPE html>
<html>
<script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js">
</script>
<body>
<div ng-app="myApp" ng-controller="nCtrl">
<h1>number Filter - Numbers</h1>
<h2>Rs.{{money | number : 2}}</h2>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('nCtrl', function($scope) {
$scope.money = 999999;
});
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js">
</script>
<body>
<div ng-app="myApp" ng-controller="datCtrl">
<p>Date = {{ today | date }}</p>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('datCtrl', function($scope) {
$scope.today = new Date();
});
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<p>Click the table headers to change the sorting order:</p>
<div ng-app="myApp" ng-controller="namesCtrl">
<table border="1" width="100%">
<tr>
<th ng-click="orderByMe('name')">Name</th>
<th ng-click="orderByMe('country')">Country</th>
</tr>
<tr ng-repeat="x in names | orderBy:myOrderBy">
<td>{{x.name}}</td>
<td>{{x.country}}</td>
</tr> </table> </div> <script>
angular.module('myApp', []).controller('namesCtrl', function($scope) {
$scope.names = [
{name:'Jani',country:'Norway'},
{name:'Carl',country:'Sweden'},
{name:'Margareth',country:'England'},
{name:'Mary',country:'England'},
{name:'Kai',country:'Norway'}
];
$scope.orderByMe = function(x) {
$scope.myOrderBy = x;
}
});
</script> </body> </html>
<!DOCTYPE html>
<html>
<script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js">
</script>
<body>
<div ng-app="myApp" ng-controller="sizeCtrl">
<ul>
<li ng-repeat="x in cars | limitTo : 5 : 0">{{x}}</li>
</ul>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('sizeCtrl', function($scope) {
$scope.cars = ["Audi",
"BMW",
"Dodge",
"Fiat",
"Ford",
"Volvo",
"Lamborghini"];
});
</script>
<p>Filter applied from first
element to the fifth element.</p>
</body>
</html>
Currency Filter
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="costCtrl">
<h1>Price: {{ price | currency }}</h1>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('costCtrl', function($scope) {
$scope.price = 58;
});
</script>
<p>The currency filter formats a number to a currency format.</p>
</body>
</html>
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="namesCtrl">
<ul>
<li ng-repeat="x in names | filter : 'i'">
{{ x }}
</li>
</ul>
</div>
<script>
angular.module('myApp', []).controller('namesCtrl', function($scope) {
$scope.names = [
'Jani',
'Carl',
'Margareth',
'Hege',
'Joe',
'Gustav',
'Birgit',
'Mary',
'Kai'
];
});
</script>
<p>This example displays only the names containing the letter "i".</p>
</body>
</html>
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="namesCtrl">
<p>Type a letter in the input field:</p>
<p><input type="text" ng-model="test"></p>
<ul>
<li ng-repeat="x in names | filter:test">
{{ x }}
</li>
</ul>
</div>
<script>
angular.module('myApp', []).controller('namesCtrl', function($scope) {
$scope.names = [
'Jani',
'Carl',
'Margareth',
'Hege',
'Joe',
'Gustav',
'Birgit',
'Mary',
'Kai'
];
});
</script>
<p>The list will only consists of names matching the filter.</p>
</body>
</html>
AngularJS Controllers
● AngularJS controllers are used to control the flow of data of AngularJS application.
● A controller is defined using ng-controller directive.
● A controller is a JavaScript object containing attributes/properties and functions.
● Each controller accepts $scope as a parameter which refers to the application/module
that controller is to control.
● Syntax:
<element ng-controller="expression">

Contents...

</element>
<!DOCTYPE html>
<html>
<head>
<title>ng-controller Directive</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js">
</script>
<script>
var app = angular.module('myApp', []);
app.controller('personCtrl', function($scope) {
$scope.fullName = function() {
return $scope.firstName + " " + $scope.lastName;
};
});
</script>
</head>
<body style="padding: 30px">
<center>
<div ng-app="myApp" ng-controller="personCtrl">
<h2>ng-controller Directive</h2>
First Name:
<input type="text" ng-model="firstName">
<br><br>
Last Name:
<input type="text" ng-model="lastName">
<br><br>
Full Name: {{fullName()}}
</div>
</center>
</body>
</html>
AngularJS Scope
● The $scope in an AngularJS is a built-in object, which contains application data and
methods.
● Can create properties to a $scope object inside a controller function and assign a
value or function to it.
● It transfer data from the controller to view and vice versa.
● There are two types of Scope in AngularJS.
○ $Scope
○ $rootScope
AngularJS Scope
● AngularJS creates and injects a different $scope object to each controller in an
application.
● the data and methods attached to $scope inside one controller cannot be accessed in
another controller.
● With the nested controller, child controller will inherit the parent controller's scope
object.
● Therefore, child controller can access properties added in parent controller but parent
controller cannot access properties added in child controller.
$rootscope
● An AngularJS application has a single $rootScope. All the other $scope objects are child
objects.
● The properties and methods attached to $rootScope will be available to all the controllers.
● Properties added in $rootscope are available in all the controllers.
● The $scope object contains various methods.
○ $new(): create new child scope
○ $destroy(): removes current scope from parent scope.
○ $eval(): executes the expression on the current scope and return result.
○ $apply(): executes an expression in angular outside the angular framework.
○ $on(): register a callback for an event.
○ $watch(): register a callback to be executed whenever model property changes.
○ $digest(): processes all the watchers of the current scope and its children.
AngularJS Scope
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<h1>{{carname}}</h1>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.carname = "Volvo";
});
</script>
</body>
</html>
AngularJS Dependency Injection
● It is a software design in which components are given their dependencies instead
of hard coding them within the component.
● It relieves a component from locating the dependency and makes dependencies
configurable.
● It also helps in making components reusable, maintainable and testable.
● AngularJS provides a supreme Dependency Injection mechanism.
AngularJS Dependency Injection

● It provides following core components which can be injected into each


other as dependencies.
○ Value
○ Factory
○ Service
○ Provider
○ Constant
Value: In AngularJS, value is a simple object. Factory: It is a function that is used to return
It can be a number, string or JavaScript object. value. When a service or controller needs a value
injected from the factory, it creates the value on
It is used to pass values in factories, services
demand. It normally uses a factory function to
or controllers during run and config phase. calculate and return the value.
//define a module var myModule = angular.module("myModule", []);

var myModule = angular.module("myModule", []); myModule.factory("myFactory", function() {

//create a value object and pass it a data. return "a value";


});
myModule.value("numberValue", 100);
myModule.controller("MyController", function($scope,
myModule.value("stringValue", "abc"); myFactory) {
myModule.value("objectValue", { val1 : 123, val2 : console.log(myFactory);
"abc"} );
})
Service: In AngularJS, service is a JavaScript Provider: In AngularJS, provider is used internally
object which contains a set of functions to to create services, factory etc. during config phase
perform certain tasks. Services are created by (phase during which AngularJS bootstraps itself). It
using service() function on a module and then is the most flexible form of factory you can create.
injected into controllers. Provider is a special factory method with a get()
function which is used to return the
//create a service which defines a method square to return value/service/factory.
square of a number.
myApp.service('CalcService', function(MathService){ //define a module
this.square = function(a) { var myApp = angular.module("myApp", []);
return MathService.multiply(a,a); //create a service using provider which defines a method
} square to return square of a number.
}); myApp.config(function($provide) {
//inject the service "CalcService" into the controller $provide.provider('MathService', function() {
myApp.controller('CalcController', function($scope, this.$get = function() {
CalcService, defaultInput) { var factory = {};
$scope.number = defaultInput; factory.multiply = function(a, b) {
$scope.result = CalcService.square($scope.number); return a * b;
$scope.square = function() { }
$scope.result = CalcService.square($scope.number); return factory;
} };
}); });
});
Constants: You cannot inject values into the module.config() function. Instead constants
are used to pass values at config phase.
mainApp.constant("configParam", "constant value");
AngularJS Routing

● We can build Single Page Application (SPA) with AngularJS.


● It is a web app that loads a single HTML page and dynamically updates
that page as the user interacts with the web app.
● AngularJS Supports SPA using routing module ngRoute.
● This routing module acts based on the url.
● When a user requests a specific url, the routing engine captures that url
and renders the view based on the defined routing rules.
ngRoute

● AngularJS ngRoute module provides routing, deep linking services and


directives for angular applications.
● We have to download angular-route.js script that contains the ngRoute
module from AngularJS official Module website to use the routing
feature.
● You can also use the CDN in your application to include this file. In this
section, We are going to use the Google CDN.
"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"
ngRoute

● If you are bundling this file into your application,


<script src = “angular-route.js”>
● Load t e ngRoute module in your AngularJS application by adding it as a
dependent module.
angular.module(‘appName’, [‘ngRoute’]);
ngView

● This directive is used to display the HTML templates or views in the


specified routes.
● Every time the current route changes, the included view changes with it
according to the configuration of the $route service.
$routeProvider

● It is used to configure the routes.


● ngRoute config() is used to configure the $routeProvider.
● The config() takes a function which takes the $routeProvider as
parameter and the routing configuration goes inside the function.
● $routeProvider has a simple API, accepting either the when() or
otherwise() method.
Built - in Helper function

1. angular.equals: angular.equals(value1, value2)


2. angular.toJson: angular.toJson(object)
3. angular.copy: angular.copy(object)
4. angular.isString: angular.isString(value1)
5. angular.isArray: angular.isArray(value)
6. angular.merge: angular.merge(destination, source)
7. angular.isDefined and angular.isUndefined:
angular.isDefined/Undefined(someValue)
8. angular.isDate: angular.isDate(value)
Built - in Helper function

9. angular.noop: angular.noop
10. angular.isElement: angular.isElement(element)
11. angular.isFunction: angular.isFunction(fn)
12. angular.identity: angular.identity(argument)
13. angular.forEach: angular.forEach(object, funcion(value,key) {//function});
14. angular.isNumber: angular.isNumber(value)
15. angular.isObject: angular.isObject(value)
16. angular.fromJson: angular.fromJson(string | object)

You might also like