AngularJS
AngularJS
Features of AngularJS
1. Data Binding
2. Architecture
3. Directives
4. Not Browser Specific
5. Codeless
6. Speed and Performance
7. Dependency Injection
i. Data Binding
ii. Architecture
iii. Directives
v. Code Less
It allows to bookmarks the web page. The page gets saved by its URL
without getting its state changed.
Whenever the request is made by a user for that page it will get
displayed in the same state as before.
Advantage of AngularJS
o Testing: Angular JS is designed in a way that we can test right from the start.
So, it is very easy to test any of its components through unit testing and end-to-
end testing.
o Model View Controller: In Angular JS, it is very easy to develop
application in a clean MVC way. You just have to split your application code into
MVC components i.e. Model, View and the Controller.
o Google supported
AngularJs framework is supported by a large community, Google.
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 Expressions
AngularJS expressions can be written inside double braces: {{ expression }}.
AngularJS expressions can also be written inside a directive: ng-bind="expression".
AngularJS will resolve the expression, and return the result exactly where the
expression is written.
AngularJS expressions are much like JavaScript expressions: They can contain literals,
operators, and variables.
Example {{ 5 + 5 }} or {{ firstName + " " + lastName }}
Example:
OUTPUT:
AngularJS Strings
AngularJS strings are like JavaScript strings:
OUTPUT:
AngularJS Object:
AngularJS Objects are like JavaScript Object So you can easily access via dot(.) operator
OUTPUT:
AngularJS Arrays:
AngularJS arrays are like JavaScript array so you can easily access via index.
OUTPUT:
AngularJS Expression capabilities and Limitations
Like JavaScript expressions, AngularJS expressions can contain literals, operators, and
variables.
ngShow Directive
The ngShow directive will show, or hide, the element
on which it is declared, based on the expression provided to it.
OUTPUT:
Ng-Init Directive
The ng-init directive is used to initializes application data or value or you can say put
the value to the variable.
ng-click Directive
The AngularJS ng-click directive facilitates you to specify custom behavior when an
element is clicked. So, it is responsible for the result what you get after clicking.
It is supported by all HTML elements.
<element ng-click="expression"></element>
OUTPUT:
OUTPUT:
Ng-Model Directive
The ng-model directive is used binds the value of HTML controls (like input) to
application data.
This directive binds the value from the web page, mostly from the input field to the
application variable. Basically, this directive allows sending data from input to
AngularJS application which can be used somewhere else
Syntax
<div ng-app = "">
<p>Type Name: <input type = "text" ng-model = "Name"></p>
</div>
ng-bind Directive
The AngularJS ng-bind directive replaces the content of an HTML element with the
value of a given variable, or expression. If you change the value of the given variable or
expression, AngularJS changes the content of the specified HTML element as well as.
This directive binds the value from the AngularJS application to the web page. i.e. It
allows forwarding data from the application to HTML tags.
Syntax:
<element ng-bind="expression"></element>
OUTPUT:
OUTPUT:
Scope in AngularJS
The $scope in an AngularJS is a built-in object, which contains application data and
methods. You can create properties to a $scope object inside a controller function and
assign a value or function to it.
The $scope is glue between a controller and view (HTML). It transfers data from the
controller to view and vice-versa.
The controller will use the data model, carry out the required processing and then pass
the output to the view which in turn is displayed to the end user.
The controller's primary responsibility is to control the data which gets passed to the
view. The scope and the view have two-way communication.
We create an AngularJS Module, myNgApp, for our application. Then we add the
controller's constructor function to the module using the .controller() method. This
keeps the controller's constructor function out of the global scope.
Note: The $ sign is used as prefix in all the built-in objects in AngularJS, so that we
can differentiate AngularJS built-in objects and other objects
First.js
OUTPUT:
Using function
The properties of the view can call "functions" on the scope. Moreover events on the
view can call "methods" on the scope
Using button click
Unit 2
For example, if you want to have your strings in either in lowercase or all in uppercase,
you can do this by using filters in Angular.
There are built-in filters such as 'lowercase', 'uppercase' which can retrieve the output in
lowercase and uppercase accordingly. Similarly, for numbers, you can use other filters.
OUTPUT
Adding Filters to Directives
orderBy
Filters are added to directives, like ng-repeat, by using the pipe character |,
followed by a filter:
OUTPUT
currency Filter
The currency filter formats a number as currency
OUTPUT:
The filter Filter
The filter filter selects a subset of an array.
The filter filter can only be used on arrays, and it returns an array containing
only the matching items.
OUTPUT:
Date Filter
The date filter is used to format a date to a specified format. The date can be a date object,
milliseconds, or a datetime string like "2016-05-05T09:05:05.035Z" By default, the format
is "MMM d, y" (May 5, 2016).
Syntax:
date: It specifies a date format either as Date object, milliseconds (string or number) or
various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.sssZ and its shorter
versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ).
format: It is optional. It is used to display the date in, which can be composed of the
following elements.
The limitTo filter returns an array or a string containing only a specified number of elements.
When the limitTo filter is used for arrays, it returns an array containing only the specified
number of items.
When the limitTo filter is used for strings, it returns a string containing, only the specified
number of characters.
When the limitTo filter is used for numbers, it returns a string containing only the specified
number of digits.
Use negative numbers to return elements starting from the end of the element, instead of the
beginning
orderBy filter:
The orderBy filter is a handy tool used in angular js.
The orderBy channel encourages you to sort an exhibit.
Of course, it sorts strings in sequential order requests and numbers in the numerical
request.
Syntax:
{{ orderBy_expression | orderBy : expression : reverse }}
Orderby(ascending )
Custom filter
<!doctype html>
<html lang="en">
<head>
<title>Example - example-filter-reverse-production</title>
<script src="angular.min.js"> </script>
</head>
<body ng-app="ReverseFilter">
<div ng-controller="ReverseController">
<input ng-model="msg" type="text"><br>
Content with No filter: {{msg}}<br>
Content after Reverse filter: {{msg|reverse}}<br>
</div>
</body>
<script>
}
return out;
};
});
app.controller('ReverseController', function($scope) {
$scope.msg = 'angular';
});
</script>
</html>
Single page applications or (SPAs) are web applications that load a single HTML page and
dynamically update the page based on the user interaction with the web application.
What is Routing in AngularJS?
AngularJS routes enable you to create different URLs for different content in your
application.
AngularJS routes allow one to show multiple contents depending on which route is
chosen.
A route is specified in the URL after the # sign.
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 website to use the routing feature.
If you are bundling this file into your application, then you can add it to your page
with below code.
<script src="angular-route.js">
angular.module('appName', ['ngRoute']);
ngView
ngView 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
$routeProvider has a simple API, accepting either the when() or otherwise() method.
app.config(function($routeProvider) {
$routeProvider
.when('/view1', {
templateUrl: 'view1.html',
controller: 'FirstController'
})
.when('/view2', {
templateUrl: 'view2.html',
controller: 'SecondController'
})
.otherwise({
redirectTo: '/view1'
});
});
templateUrl property defines which HTML template AngularJS should load and
display inside the div with the ngView directive.
controller property defines which controllers should be used with the HTML template.
When the application is loaded, path is matched against the part of the URL after the #
symbol. If no route paths matches the given URL the browser will be redirected to the
path specified in the otherwise() function.
Example:
Index.html
<!DOCTYPE html>
<html>
<script src="angular.min.js"> </script>
<script src="angular-route.min.js"></script>
<body ng-app="myApp">
<p><a href="#/!">
<img src="logo.png" alt="logo" style="width: 50 height:50;"></a></p>
<a href="#!/courses">Courses</a>
<br>
<a href="#!/internships">Internships</a>
<div ng-view></div>
<script>
var app = angular.module("myApp", ["ngRoute"]);
app.config(function($routeProvider) {
$routeProvider
.when("/", {
template : '<h1>Welcome to Institute</h1> <p> Click on the links to
change this content </p>'
})
.when("/courses", {
template : `<h1>Courses Offered</h1> <p> <ul> <li>Machine Learning
Foundation</li>
<li>Web Classes</li> <li>System
Design</li>
</ul></p>`
})
.when("/internships", {
template : `<h1>Hire With Us</h1>
<p>
<ul>
<li>Software Developer</li>
<li>Technical Content Writer</li>
<li>Technical Content Engineer</li>
</ul>
</p>`
});
});
</script>
</body>
</html>
Example:
<!DOCTYPE html>
<html >
<head>
<title>Routing</title>
<script src="angular.min.js"></script>
<script src="angular-route.min.js"></script>
<script>
angular.module("DemoApp", ['ngRoute'])
.controller("DemoController", function($scope) {
$scope.title = "Simple Router Example";
})
.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/abc', {
template: '<h2>ABC</h2> from the template',
}).
when('/def', {
templateUrl: 'def.html',
}).
otherwise({
redirectTo: '/'
});
}]);
</script>
</head>
Route Parameters
You can embed parameters into the route path. Here is an AngularJS route path parameter
example:
#/books/12345
This is a URL with a route path in. In fact it pretty much consists of just the route path. The
parameter part is the 12345 which is the specific id of the book the URL points to.
AngularJS can extract values from the route path if we define parameters in the route paths when
we configure the $routeProvider. Here is the example $routeProvider from earlier, but with
parameters inserted into the route paths:
Your controller functions can get access to route parameters via the
AngularJS $routeParams service like this:
Example:
<!DOCTYPE html>
<html>
<head>
<title>AngularJS Routing with Prameters Example</title>
<script src="angular.min.js"></script>
<script src="angular-route.min.js"></script>
<script>
var app = angular.module("routesApp", ['ngRoute']);
app.config(['$routeProvider',function ($routeProvider) {
$routeProvider.when('/routeURL1/:userId', {
templateUrl: 'sample1.html',
controller: 'sample1Controller'
}).
when('/routeURL2', {
templateUrl: 'sample2.html',
controller: 'sample2Controller'
}).
otherwise({
redirectTo: '/login'
});
}
]);
app.controller('sample1Controller',function($scope,$routeParams){
$scope.uid = $routeParams.userId;
})
app.controller('sample2Controller',function($scope){
$scope.message='Test Sample Page 2 URL';
})
</script>
</head>
<body>
<h2>AngularJS Routing with Parameters Example</h2>
<div ng-app="routesApp">
<ul>
<li>
<a href="#!/routeURL1/34124">Route1 with Parameters</a>
</li>
<li>
<a href="#!/routeURL2">Sample Route2</a>
</li>
</ul>
<div ng-view></div>
</div></body></html>
When a route change events occurs the following events are triggered,
$locationChangeStart
$routeChangeStart
$locationChangeSuccess
$routeChangeSuccess
$routeChangeStart
When routeChangeStart is triggered a function is called and that function will have parameters
like event which is called, the second parameter is the next parameter in which the next route is
called and the last parameter is current parameter to stick to that route only.
Now the next thing which we have to do is to display a confirmation which we will do using
JavaScript confirm function,
Now we want the confirmation if the user clicks ok it will return true and route to the other URL
and if users click cancel it will return false and it will stay on the current route only. So when
user clicks on cancel it should return false so we are using NOT operator,
1. if (!confirm("Are you sure you want to Navigate away from this page ")) {
2.
3. }
To cancel route Change we are going to use event object -- we use prevent default function as,
<div>
<p><a href = "#!/viewLink1">Link 1</a></p>
<p><a href = "#!/viewLink2">Link 2</a></p>
<div ng-app = "mainApp" ng-controller = "GFGController">
<div ng-view></div>
</div>
<script>
var mainApp = angular.module("mainApp", ['ngRoute']);
mainApp.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/viewLink1', {
template: "<p> This is Link 1 </p>"
})
.when('/viewLink2', {
template: "<p> This is Link 2 </p>"
})
.otherwise({
redirectTo: '/'
});
}]);
$rootScope.$on('$locationChangeStart',function(event,next,current)
{
if(!confirm("Are you sure want to navigate away from this
page "+next))
event.preventDefault();
});
$rootScope.$on('$routeChangeSuccess', function () {
console.log("route changed");
});
});
</script>
</body>
</html>
ng-include in AngularJS
AngularJS has a built-in directive to include the functionality from other AngularJS files by
using the ng-include directive.The primary purpose of the “ng-include directive” is used to
fetch, compile and include an external HTML file in the main AngularJS application.These are
added as child nodes in the main application. The ng-include attribute’s value can also be an
expression, that returns a filename. All HTML element supports this.
Syntax:
<element ng-include="filename" onload="expression" autoscroll="expression" >
Content...</element>
Note: Here the onload and autoscroll parameter are optional , onload define an expression to
evaluate when the included file is loaded and autoscroll define whether or not the included
section should be able to scroll into a specific view.
Example:1
Child.html
<html>
<body>
Demonstration of ng-include directive
</body>
</html>
Index.html
<!DOCTYPE html>
<html>
<head>
<title>Expression</title>
</head>
<body ng-app="">
<script src="angular.min.js"></script>
<h1> Angular </h1>
<div>
<div ng-include="'child.html'">
</div>
</body>
</html>
Example:2
Index.html
<!DOCTYPE html>
<html>
<head>
<title>Expression</title>
</head>
<body>
<script src="angular.min.js"></script>
<script src="i1.js"></script>
<h1> Angular Include example</h1>
<div ng-app="myapp" ng-controller="mycontroller">
<select ng-model="E">
<option value="empTable.html">Table</option>
<option value="emp_lst.html">List</option>
</select>
<div ng-include="E"></div>
</div>
</body>
</html>
emp_lst.html
<html>
<head>
</head>
<body>
<script src="angular.min.js"></script>
<script src="i1.js"></script>
<h1> Employee List </h1>
<div ng-app="myapp" ng-controller="mycontroller">
<ul ng-repeat="emp in employee">
<li>{{emp.name}}
<ul>
<li>{{emp.gender}}
<li>{{emp.salary}}
</ul>
</ul>
</div>
</body>
</html>
empTable.html
<html>
<head>
</head>
<body>
<script src="angular.min.js"></script>
<script src="i1.js"></script>
<h1> Dsiplay in Table</h1>
<div ng-app="myapp" ng-controller="mycontroller">
<table border=1>
<tr ng-repeat="emp in employee">
<td>{{emp.name}}</td>
<td>{{emp.gender}}</td>
<td>{{emp.salary}}</td>
</tr>
</table>
</div>
</body>
</html>
ng-src Directive
The ng-src Directive in AngularJS is used to specify the src attribute of an <img> element. It
ensures that the wrong image is not produced until AngularJS has been evaluated. It is supported
by <img> element.
Syntax:
<img ng-src="url"> </img>
Example:
<!DOCTYPE html>
<html>
<head>
<title>Welcome</title>
<script src="angular.min.js"></script>
</head>
<body ng-app="Example">
<div ng-controller="ExampleController">
<img ng-src="{{pic}}" height=300 width=300/>
</div>
<script>
var app = angular.module("Example", []);
app.controller('ExampleController', function ($scope) {
$scope.pic = "tom.jpg";
});
</script>
</body>
<html>
<head>
<title>Welcome</title>
<script src="angular.min.js"></script>
</head>
<body ng-app="myApp" ng-controller="myController">
<div>
<h3 >Images in list using ng-src</h3>
<ul ng-repeat="pic in pics">
<li><img ng-src="{{pic.url}}" style="height:300px;width:300px" /><span style="font-
size:14">{{pic.Name}}</span></li>
</ul>
</div>
<script>
var app = angular.module("myApp", []);
app.controller('myController', function ($scope) {
$scope.pics = [{ url: "mickey.jpg", Name: "Mickey" }, { url: "mickey2.jpg", Name:
"Mickey" }];
});
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>Welcome</title>
<script src="angular.min.js"></script
</head>
<body ng-app="myApp" ng-controller="myController">
<div>
<h3>Images in table using ng-src</h3>
<table border=1>
<tr>
<th>Name</th>
<th>Capital</th>
<th>Currency</th>
<th>Flag</th>
</tr>
<tr ng-repeat="country in countries">
<td>{{country.Name}}</td>
<td>{{country.Capital}}</td>
<td>{{country.Currency}}</td>
<td><img ng-src="{{country.Flag}}" width="50" height="30" /></td>
</tr>
</table>
</div>
<script>
var app = angular.module("myApp", []);
app.controller('myController', ['$scope', function ($scope) {
$scope.countries =
[{ Name: "India", Capital: "New Delhi", Currency: "Indian rupee", Flag: "india.png" },
{ Name: "Afghanistan", Capital: "Kabul", Currency: "Afghani", Flag: "afghanistan.png" },
{ Name: "Nepal", Capital: "Kathmandu", Currency: "Nepalese rupee", Flag: "nepal.jpg" }]
}]);
</script>
</body>
</html>
AngularJS Service
AngularJS services are JavaScript functions for specific tasks, which can be reused throughout
the application.
AngularJS includes services for different purposes. For example, $http service can be used to
send an AJAX request to the remote server. AngularJS also allows you to create custom service
for your application
AngularJS provides many inbuilt services. For example, $http, $route, $window, $location, etc.
Each service is responsible for a specific task such as the $http is used to make ajax call to get
the server data, the $route is used to define the routing information, and so on. The inbuilt
services are always prefixed with $ symbol.
$log Service
AngularJs includes logging service $log, which logs the messages to the browser's console.
The $log service includes different methods to log the error, information, warning or debug
information. It can be useful in debugging and auditing.
$interval Service
AngularJS includes $interval service which performs the same task as setInterval() method in
JavaScript. The $interval is a wrapper for setInterval() method, so that it will be easy to override,
remove or mocked for testing.
The $interval service executes the specified function on every specified milliseconds duration.
AngularJs includes $window service which refers to the browser window object.
In the JavaScript, window is a global object which includes many built-in methods like alert(),
prompt() etc.
The $window service is a wrapper around window object, so that it will be easy to override,
remove or mocked for testing. It is recommended to use $window service in AngularJS instead
of global window object directly.
In this method, we first define a factory and then assign method to it.
var mainApp = angular.module("mainApp", []);
mainApp.factory('MathService', function() {
var factory = {};
factory.multiply = function(a, b) {
return a * b
}
return factory;
});
mainApp.service('CalcService', function(MathService) {
this.square = function(a) {
return MathService.multiply(a,a);
}
});
Example1:
Cal.html
<html>
<head>
<script src="angular.min.js"></script>
<script src="calc_ser.js"></script>
</head>
<body ng-app="MyApp">
<div ng-controller="myctrl">
First Value : <input type="number" ng-model="num1"/><br>
Second Value : <input type="number" ng-model="num2"/><br>
Result : {{ result }}<br>
<button ng-click="sum()" > SUM </button>
<button ng-click="mult()" > Multiplication </button>
</div>
</body>
</html>
calc_ser.js
var app=angular.module("MyApp",[]);
app.service("calcSer",function(){
this.add = function (num1,num2) {
return parseInt(num1)+parseInt(num2);
}
this.mul = function (num1,num2) {
return parseInt(num1)*parseInt(num2);
}
});
app.controller('myctrl',function($scope,calcSer){
$scope.num1=10;
$scope.num2=10;
$scope.result=0;
$scope.sum=function(){
$scope.result=calcSer.add($scope.num1,$scope.num2)
}
$scope.mult=function(){
$scope.result=calcSer.mul($scope.num1,$scope.num2)
}
}
);
Example2:
<!DOCTYPE html>
<html>
<script src="angular.min.js"></script>
<body>
<ul>
<li ng-repeat="x in counts">{{x | myFormat}}</li>
</ul>
<p>This filter uses a service that converts numbers into hexadecimal values.</p>
</div>
<script>
var app = angular.module('myApp', []);
app.service('hexafy', function() {
this.myFunc = function (x) {
return x.toString(16);
}
});
app.filter('myFormat', function(hexafy) {
return function(x) {
return hexafy.myFunc(x);
};
});
app.controller('myCtrl', function($scope) {
$scope.counts = [255, 251, 200];
});
</script>
</body>
</html>
AngularJS Validation
Directive Description
Directive Description
ng-required Sets required attribute on an input field.
ng-minlength Sets minlength attribute on an input field.
ng-maxlength Sets maxlength attribute on an input field. Setting the attribute to a negative or non-numeric value,
allows view values of any length.
ng-pattern Sets pattern validation error key if the ngModel value does not match the specified RegEx
expression.
Property Description
$error $error object contains all the validation attributes applied to the specified element.
$pristine Returns true if the user has not interacted with control yet else returns false.
$valid Returns true if the model is valid
$invalid Returns true if the model is invalid
$dirty Returns true if user changed the value of model at least once
$touched Returns true if the user has tabbed out from the control.
$untouched Returns true if the user has not tabbed out from the control.
<!DOCTYPE html>
<html>
<head>
<title>
AngularJs Checkbox</title>
<script src="angular.min.js"></script>
<script>
var app = angular.module('checkboxApp', []);
app.controller('checkboxCtrl', function ($scope) {
$scope.validationmsg = false;
$scope.checkvalidation = function () {
var chkselct = $scope.chkselct;
if (chkselct == false || chkselct == undefined)
$scope.validationmsg = true;
else
$scope.validationmsg = false;
}
});
</script>
</head>
</body>
</html>
Example text field min/max char Validation
<html>
<head>
<title>
AngularJs Example to Use Both ng-minlength, ng-maxlength for Form Validation
</title>
<script src="angular.min.js"></script>
<script type="text/javascript">
var app = angular.module('ngminmaxlengthApp', []);
app.controller('ngminmaxlengthCtrl', function ($scope) {
$scope.sendForm = function () {
$scope.msg = "Form Validated";
};
});
</script>
</head>
<body>
<div ng-app="ngminmaxlengthApp" ng-controller="ngminmaxlengthCtrl">
<h3>AngularJs Example to Use Both ng-minlength, ng-maxlength</h3>
<form name="personForm" novalidate ng-submit="sendForm()">
Pin Code: <input type="text" name="pincode" ng-model="txtpin" ng-minlength="3" ng-
maxlength="5" required />
<span style="color:Red" ng-show="personForm.pincode.$error.required"> Required! </span>
<span style="color:Red" ng-
show="personForm.pincode.$dirty&&personForm.pincode.$error.minlength"> Minimum 3
Characters Required </span>
<span style="color:Red" ng-
show="personForm.pincode.$dirty&&personForm.pincode.$error.maxlength"> Maximum 5
Characters Allowed </span>
<br /><br />
<button type="submit">Submit Form</button><br /><br />
<span>{{msg}}</span>
</form>
</div>
</body>
</html>
Example mobile number Validation ng-pattern
<!DOCTYPE html>
<html>
<head>
<title>
AngularJs ng-pattern Form Validation Example
</title>
<script src="angular.min.js"></script>
<script type="text/javascript">
var app = angular.module('ngpatternApp', []);
app.controller('ngpatternCtrl', function ($scope) {
$scope.sendForm = function () {
$scope.msg = "Form Validated";
};
});
</script>
</head>
<body>
<div ng-app="ngpatternApp" ng-controller="ngpatternCtrl">
<h3>AngularJs ng-pattern with Number Validation Example</h3>
<form name="personForm" novalidate ng-submit="personForm.$valid &&sendForm()">
Pin Code:<input type="text" name="pincode" ng-model="txtpin" ng-pattern="/^[0-9]{1,5}$/"
required />
<span style="color:Red" ng-show = "personForm.pincode.$dirty &&
personForm.pincode.$invalid">
<span style="color:Red" ng-show="personForm.pincode.$error.required"> Required! </span>
<span style="color:Red" ng-show="personForm.pincode.$error.pattern">Only Numbers
Allowed, Maximum 5 Characters</span>
</span>
<br /><br />
});
});