AngularJS
DR. SANJAY P. BHAKKAD
ASSOCIATE PROFESSOR,
IMSCD&R AHMEDNAGAR
Introduction
What is AngularJS?
AngularJS is a modern JavaScript framework from
Google, commonly used to work with Single Page
Applications (SPAs).
AngularJS is primarily based on declarative HTML
attributes that you can add to your HTML page with
a <script> tag.
The library is called Angular because HTML uses
angular-shaped brackets.
AngularJS is open sourced.
Introduction
AngularJS is client-sided, so all these things are
happening in browsers and you get the elegance of
standalone application.
AngularJS extends HTML attributes with Directives
and binds data to HTML with Expressions.
It’s a framework for Dynamic web applications.
AngularJS makes use of declarative programming for
building UI.
It’s a MVC structured framework.
Introduction
Why to use AngularJS?
Allows you to reuse components
An easy way of two-way bindings
You can directly call the code-behind code in your
html
You can validate forms and input fields before
submitting it without writing a single line of code
Allows you to control complete DOM structure
show/hide, changing everything with AngularJS
properties
Model-View-Controller (MVC)
MVC structure provides the clear
separation between
managing the data (model),
the application logic (controller) &
presenting the data to the user (view)
The view gets data from the model to display to the user.
When user interacts with the application by clicking or
typing, the controller responds by changing data in the
model.
Finally, the model notifies the view that a change has
occurred so that it can update what it displays.
Model-View-Controller (MVC)
VIEW
View in an application is a part which is rendered in
a browser through which user can interact or see
whatever data has been requested.
In an AngularJS application view is the DOM,
composed of directives, filters and data-bindings.
Model-View-Controller (MVC)
CONTROLLER
Controller holds all of our application logic. In
AngularJS the controllers are JavaScript classes.
The Controller controls and prepares the data into
the form so that it can be rendered at the View.
The controller is responsible for communicating the
server code to fetch the data from a server using Ajax
requests and send the data to back-end server from
Views.
Model-View-Controller (MVC)
MODEL
Model is the bridge standing between Controllers and
Views.
In AngularJS, the model data is stored in Object
properties.
There can be a controller which we can bind to two or
more views. In reality the Controller is blank about views
and has no information about the views
Similarly View is independent of logic implemented or
data present in the Controller.
And, model acts as the communication tunnel between
the Views and Controller.
Hello, World : Example
Hello.html
<!DOCTYPE html>
<html ng-app>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.4/angular.mi
n.js"></script>
<script src="controllers.js"></script>
</head>
<body>
<div ng-controller = 'HelloController'>
<p>{{greeting.text}}, World</p>
</div>
</body>
</html>
Hello, World : Example
controller.js
function HelloController ($scope) {
$scope.greeting = {text: 'Hello'};
}
Note that the part of DOM is updated separately,
rather than updating the whole page.
Here, we have merged template HTML strings with
data, and inserted the result where we want it in the
DOM.
Data binding
If you want to insert fresher data into the UI, or
change the data based on user input, you need to do
some non-trivial work.
But, we could have hall this work done for us without
writing (additional) code.
For this, we could just declare which part of the UI
map to which JavaScript properties and have them
sync automatically.
Called data-binding.
MVC will do this for you.
Hello, World – Live : Example
In this example, we add a text input that can
change the value of greeting.text as the user types.
HelloDynamic.html
<div ng-controller = 'HelloController'>
<input ng-model='greeting.text'>
<p>{{greeting.text}}, World</p>
</div>
Now, we have UI that will dynamically update.
Angular would automatically update both the input and the text
in the curly braces by getting the values from the controller.
AngularJS : First Program
<!DOCTYPE html>
<html ng-app>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.4/angular.min.js">
</script>
<script src="controllers.js"></script>
</head>
<body>
<div ng-controller = 'HelloController'>
<input ng-model='greeting.text'>
<p>Hello {{greeting.text}}!</p> See: Controller.js
</div>
function HelloController ($scope) {
</body>
</html> $scope.greeting = {text: 'Students'};
See: HelloDynamic.html }
Basic building blocks of AngularJS
Invoking AngularJS
Any application must do two things to start Angular:
1. Load the angular.js library
2. Tell Angular which part of the DOM it should manage with
the ng-app directive
Loading the Script:
You can load the script from Google’s content
delivery network (CDN), like so:
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.4/angular.min.js">
</script>
Directives
In earlier programs we have seen several new attributes
which are not part of the HTML.
For example
double-curly notation, for data binding,
ng-controller, for specifying which controller oversees which part of
the view
ng-model, which binds an input to part of the model
We call these HTML extension as directives.
Angular comes with many directives that help you define
the view for your app.
They can declaratively set up how your application works
or be used to create reusable components.
You can also create your own directives.
Directives
ng-app
The ng-app directive defines an AngularJS
application.
We use this directive to auto-bootstrap an AngularJS
application.
The ng-app directive designates the root element of
the application and is typically placed near the root
element of the page - e.g. on the <body> or <html>
tags.
If ng-app directive is found, that will become the
root scope of the app.
ng-app : Syntax
<element ng-app="modulename">
...
content inside the ng-app root element can contain
AngularJS code
...
</element>
<body ng-app="">
<p>My first expression: {{ 5 + 5 }}</p>
</body>
modulename is Optional, Specifies the name of a module
to load with the application.
See ng-appEx.html
Directives
ng-controller
In AngularJs, Controllers are the JavaScript classes
used to manage the areas of the page.
AngularJS applications are controlled by controllers.
The ng-controller directive defines the application
controller.
ng-controller : Example
<div ng-app="myApp" ng-controller="myCtrl">
First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{firstName + " " + lastName}}
</div>
<script>
var appModule = angular.module('myApp', []);
appModule.controller('myCtrl', function($scope) {
$scope.firstName = “Sanjay";
$scope.lastName = “Bhakkad";
});
</script> See NameEx.html
Code Explained
Controller is a part of the module, which provides a
namespace for related parts of your application.
We then called the Angular object to create a module named
myApp
Then we pass our controller’s function to call the module’s
controller function.
AngularJS will invoke the controller with a $scope object.
In AngularJS, $scope is the application object (the owner of
application variables and functions).
The controller creates two properties (variables) in the scope
(firstName andlastName).
The ng-model directives bind the input fields to the
controller properties (firstName and lastName).
ng-controller : Example
Controller Methods
The example above demonstrated a controller object
with two properties: firstName and lastName.
A controller can also have methods (variables as
functions):
Controller with method : Example
<div ng-app="myApp" ng-controller="personCtrl">
First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{fullName()}}
</div>
<script>
var app = angular.module('myApp', []);
app.controller('personCtrl', function($scope) {
$scope.firstName = “Sanjay";
$scope.lastName = “Bhakkad";
$scope.fullName = function() {
return $scope.firstName + " " + $scope.lastName;
};
});
</script>
See FullNameEx.html
ng-controller : Example
Controllers In External Files
In larger applications, it is common to store controllers in
external files.
Just copy the code between the <script> tags into an
external file named personController.js:
var app = angular.module('myApp', []);
app.controller('personCtrl', function($scope) {
$scope.firstName = “Sanjay";
$scope.lastName = “Bhakkad";
$scope.fullName = function() {
return $scope.firstName + " " + $scope.lastName;
};
}); See personController.js
Controller in External File : Example
Now, refer that script file into your html page.
<div ng-app="myApp" ng-controller="personCtrl">
First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{fullName()}}
</div>
<script src="personController.js"></script>
See NameExternalCtrlEx.html
Directives
ng-init
The ng-init directive initializes application data.
Example:
<div ng-app="" ng-init="firstName=‘Sanjay'">
<p>Input something in the input box:</p>
<p>Name: <input type="text" ng-model="firstName"></p>
<p>You wrote: {{ firstName }}</p>
</div>
See ng-initEx.html
Directives
Data Bindings
Data binding in AngularJS is the synchronization between the
model and the view.
Data Model
AngularJS applications usually have a data model. The data
model is a collection of data available for the application.
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.firstname = “Sanjay";
});
HTML View
The HTML container where the AngularJS application is
displayed, is called the view.
The view has access to the model, and there are several ways
of displaying model data in the view, as:
Directives
HTML View
1. You can use the ng-bind directive, which will bind the
innerHTML of the element to the specified model property:
<p ng-bind="firstname"></p>
2. You can also use double braces {{ }} to display content from
the model:
<p>{{firstname}}</p>
3. Or you can use the ng-model directive on HTML controls to
bind the model to the view.
<input ng-model="firstname">
See dataBindingsEx.html
Directives
Data Binding
Data binding shown via {{ }} interpolation notation lets us insert
the value of a variable into part of the page and keep it in sync.
The {{ }} sets up a one-way relationship that says “insert a value
here.”
If you want to keep changes in sync with your model use ng-
model.
The {{ firstName }} expression, in the example above, is an
AngularJS data binding expression.
Data binding in AngularJS binds AngularJS expressions with
AngularJS data.
E.g.: {{ firstName }} is bound with ng-model="firstName".
Directives
ng-model
The ng-model directive binds the value of HTML
controls (input, select, textarea) to application data.
The ng-model directive can also:
Provide type validation for application data (number, email,
required).
Provide status for application data (invalid, error).
Provide CSS classes for HTML elements.
Bind HTML elements to HTML forms.
ng-model : Example (Static)
<div ng-app="myApp" ng-controller="myCtrl">
Name: <input ng-model="name">
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.name = "Sanjay Bhakkad";
});
</script>
See ng-modelEx.html
ng-model : Example (Two Way Bindings)
<div ng-app="myApp" ng-controller="myCtrl">
Name: <input ng-model="name">
<h1>You entered: {{name}}</h1>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.name = “Sanjay Bhakkad";
});
</script>
See ng-modelEx2.html
Two Way Bindings
Data binding in AngularJS is the synchronization
between the model and the view.
When data in the model changes,
the view reflects the change, and
when data in the view changes, the model is
updated as well.
This happens immediately and automatically, which
makes sure that the model and the view is updated at
all times.
Directives
ng-repeat
The ng-repeat directive repeats a set of HTML, a
given number of times.
The set of HTML will be repeated once per item in a
collection.
The collection must be an array or an object.
Note: Each instance of the repetition is given its
own scope, which consist of the current item.
ng-repeat : Example 1
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js"></script>
<body>
<div ng-app="" ng-init="names=['Ajay','Sanjay','Vijay']">
<p>Looping with ng-repeat:</p>
<ul>
<li ng-repeat="x in names">
{{ x }}
</li>
</ul>
</div>
</body>
</html> See RepeatEx1.html
ng-repeat : Example 2 – Using Controller
<body ng-app="myApp" ng-controller="myCtrl">
<h1 ng-repeat="x in records">{{x}}</h1>
<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.records = ["Sanjay Bhakkad",
"Mahesh Potdar",
"U. H. Nagarkar",
"Hari Shankar Rai"]
});
</script>
</body>
See ngRepeatEx.html
ng-repeat : Example 3
Using External Controller
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js"></script>
<script src="recordsCtrl.js"></script>
<body ng-app="myApp" ng-controller="myCtrl">
<div ng-repeat="x in records"> var app = angular.module("myApp", []);
<span>{{x.name}}</span>, app.controller("myCtrl", function($scope) {
<span>{{x.age}}</span> $scope.records = [
{name:'Sanjay Bhakkad', age:40},
</div>
{name:'Mahesh Potdar', age:45},
{name:'U. H. Nagarkar', age:50},
</body>
{name:'Hari Shankar Rai', age:35}]
</html> });
See RepeatEx2.html File: recordsCtrl.js
ng-repeat : Example 4 - Table Creation
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js"></script>
<script src="recordsCtrl.js"></script>
<body ng-app="myApp" ng-controller="myCtrl">
<table>
<tr>
<th>No.</th>
<th>Name</th>
<th>Age</th> var app = angular.module("myApp", []);
</tr> app.controller("myCtrl", function($scope) {
<tr ng-repeat="x in records">
$scope.records = [
<td>{{ $index + 1 }}</td>
<td>{{ x.name}}</td>
{name:'Sanjay Bhakkad', age:40},
<td>{{ x.age}}</td> {name:'Mahesh Potdar', age:45},
</tr> {name:'U. H. Nagarkar', age:50},
</table> {name:'Hari Shankar Rai', age:35}]
</body>
});
</html>
See RepeatEx3.html File: recordsCtrl.js
AngularJS : Filters
Filters can be added in AngularJS to format data.
Filters allow you to declare how to transform data for
display to the user within an interpolation in your template.
The syntax for using filters is:
{{ expression | filterName : parameter1 : … parameterN }}
expression is any Angular expression,
filterName is the name of the filter you want to use, and
the parameters to the filters are separated by colons.
The parameters themselves can be any valid Angular expression.
Filters can also be chained with additional pipe symbols in the
bindings. For example
{{ 12.9 | currency | number:0 }} displays $13
AngularJS : Filters
AngularJS provides filters to transform data:
currency : Format a number to a currency format.
date : Format a date to a specified format.
filter : Select a subset of items from an array.
json : Format an object to a JSON string.
limitTo : Limits an array/string, into a specified number of
elements/characters.
lowercase : Format a string to lower case.
number : Format a number to a string.
orderBy : Orders an array by an expression.
uppercase : Format a string to upper case.
AngularJS Filter Examples
Create an external controller file : employeeRecords.js
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.records = [
{name:'Sanjay Bhakkad', joinDt:'2016-06-01', salary:40000, dept:'sales'},
{name:'Ganesh Avhad', joinDt:'1980-12-21', salary:30000, dept:'purchase'},
{name:'Jaydeep Girase', joinDt:'2015-12-15', salary:20000, dept:'sales'},
{name:'Aayushi Sharma', joinDt:'2000-11-25', salary:35000, dept:'purchase'},
{name:'Manish Joshi', joinDt:'2014-05-10', salary:22000, dept:'hr'},
{name:'Komal Dongre', joinDt:'2005-11-30', salary:15000, dept:'hr'}
]
});
AngularJS Filter Examples
LowerCaseUpperCaseFilters.html
DateFilter.html
CurrencyFilter.html
LimitToFilter.html
OrderByFilter.html
Filter_Filter.html
NumberFilter.html
JsonFilter.html