SlideShare una empresa de Scribd logo
1 de 34
Angular JS
and Java
(Spring,
Struts and
Hibernate)
…?

Hey All,
I am
Preetam Dwivedi
What is “Angular JS” ?

AngularJS is an open-source JavaScript framework,
maintained by Google, that assists with
running single-page applications. Its goal is to
augment web-based applications with model–view–
controller (MVC) capability, in an effort to make
both development and testing easier.
AngularJS allows the developer to specify custom and
reusable HTML tags that moderate the behavior of
certain elements these attributes are called ‘Diretives’.
Example: ng-app , ng-model etc.
Why “Angular JS” ?

• Defines various ways to organize web app at client
side.
• Enhances HTML using various directives, attributes
and templates.
• Encourage 2-way data binding
• Encourage MVC
• Code reuse
• Good for SPAs
Angular JS: MVC

View
3. Implements the business
Logic on response data
and bind it to view

Model

1. Event or User Action
or View Load

Controller

2. Maps to particular model
after fetching the data
Angular JS: Core Concepts

Bootstrap
Data Binding
Directives
Expressions
Filters
Controllers
Dependency Injection
Views and Routing
Services
$digest
Angular JS: Bootstrap

<!doctype html>
<html lang="en" ng-app>
<head>
<meta charset="utf-8">
<title>My HTML File</title>
<script src="angular.js"></script>
</head>
<body>
…..
</body>
</html>

The ng-app attribute represents
an Angular directive
named ngApp.
The ngApp found in the
document will be used to define
the root element to autobootstrap as an application.
What happens during bootstrapping..?

There are 3 important things that happen during the app
bootstrap:
• The injector that will be used for dependency injection is
created.
• The injector will then create the root scope that will become
the context for the model of our application.
• Angular will then compile the DOM starting at
the ngApp root element, processing any directives and
bindings found along the way.
Angular JS: Data Binding

Data-binding in Angular
web apps is the automatic
synchronization of data
between the model and
view components.
First the template
(uncompiled HTML) is
compiled on the browser,
and second, the
compilation step produces
a live view.
Angular JS: Directives
I am ng-model and i am a
directive.

<input ng-model=“hell">

Directives are markers on a DOM element (such as an
attribute, element name, or CSS class) that tell
AngularJS's HTML compiler ($compile) to attach a
specified behavior to that DOM element or even transform
the DOM element and its children.
Angular provide some in-built directives like ngApp(ngapp), ngModel(ng-model), ngIf(ng-if) etc.
Angular JS: Directives…
Do I need to get compiled…?

<input ng-model=“hell">

What does it mean to "compile" an HTML template?
For AngularJS, "compilation" means attaching event
listeners to the HTML to make it interactive. The reason
the term "compile" is used that the recursive process of
attaching directives mirrors the process of compiling source
code in compiled programming languages.
Angular JS: Expressions

{{ expression }}

1+2=3

{{a.b.c}}

I am an expression. I use $parse
service to evaluate.

1+2={{1+2}}

Expression evaluation is
forgiving to undefined and null.
It means that if any of a/b/c is
null or undefined it will not
throw exception and show
nothing(blank).
Angular JS: Filters

{{ 1.234 | number:2 }}

I am a Filter. I will show up to 2
decimal points only i.e. 1.23

A filter formats the value of an expression for display to the
user.
They can be used in view templates, controllers or services and
it is easy to define your own filter.
{{ expression | filter }}
{{ expression | filter1 | filter2 | ... }}
{{ expression | filter:arg1 : arg2 ... }}
Its too much to remember.
Lets see an example.
Angular JS: Controllers
In Angular, a Controller is a
JavaScript constructor function that
is used to augment the Angular
Scope.
When a Controller is attached to the
DOM via the ng-controller directive,
Angular will instantiate a new
Controller object, using the specified
Controller's constructor function. A
new child scope will be available as
an injectable parameter to the
Controller's constructor function
as $scope.

I am a controller. I contain all
business logics.

<div
ng-controller=“hellCtrl">
{{msg}}
</div>
function hellCtrl($scope)
{
$scope.msg = ‘Hell!!!';
}
Angular JS: Controllers…
Please use me correctly.

function hellCtrl($scope)
{
$scope.msg = ‘Hell!!!';
}

Do not use Controllers for:
• Any kind of DOM manipulation — Controllers should contain
only business logic.
• Input formatting (use angular form controls instead).
• Output filtering (use angular filters instead).
• Sharing stateless or stateful code across
Controllers(use angular services instead).
• Managing the life-cycle of other components (for example, to
create service instances).
Angular JS: Dependency Injection
$scope and hellSvc are two
services which need to be
injected into the controller.

function hellCtrl($scope,
hellSvc)
{ ... }

Dependency Injection (DI) is a software design pattern that
deals with how code gets hold of its dependencies.
There are only 3 ways an object or a function can get a hold of
its dependencies:
• The dependency can be created, using the new operator.
• The dependency can be looked up by referring to a global
variable.
• The dependency can be passed in to where it is needed.
Angular JS: Views and Routing

Sample App Router Config
var app= angular.module(‘app', [
'ngRoute‘, ‘appCtrl’ ]);
app.config(['$routeProvider',
function($routeProvider) {
$routeProvider.when('/home',
{
templateUrl: 'partials/home.html',
controller: ‘homeCtrl'
}).otherwise({
redirectTo: '/error’ });
}]);

$route is used for deep-linking
URLs to controllers and views
(HTML partials). It
watches $location.url() and tries
to map the path to an existing
route definition.
Routing requires
the ngRoute module to be
installed.
We can define routes
through $routeProvider’s API.
Angular JS: Services

What are Angular Services?
Angular services are singletons objects or functions that carry out
specific tasks common to web apps. Angular has a number of built
in services, such as the $http service.
Using $inject for injection

Using inline injection

var ctrl= function($location) { ... };
ctrl.$inject = ['$location'];

var svc= function($http) { ... };

myModule.controller(‘ctrl', ctrl);

myModule.factory(‘svc', ['$http',
svc]);
Angular JS: Services and DI
xTended

app.config(function($provide) {
$provide.factory('greeting',
function() {
return function(name) {
alert("Hello, " + name);
};
}); });
var greeting =
$injector.get('greeting');
greeting(‘Cloak’);
Angular JS: Creating Services

All services are defined by using $provider service and it’s
respective methods provider, factory and service.
These methods are also available on the module object so you can
use them without injecting $provider service.
Using angular module

Using $provider service

var myModule =
angular.module('myModule', []);
myModule.factory('serviceId',
function() {
var inst;
…
return inst;
});

angular.module('myModule', [],
function($provide) {
$provide.factory('serviceId',
function() {
var inst;
…
return inst;
});});
Angular JS: Creating Services…
Creating services using service. Service is suitable for cases when
you have a ready function that you need to share throughout the
app without any “preprocessing”. It expects to receive a constructor
which it then invokes by using new and then returns a result.
Using service

angular.module(‘hell', []).service(‘hellService', function(){
this.greet = function (name) {
return ‘Welcome to Hell : ' + name;
}
});
function hellController( hellService) {
hellService.greet(‘Cloak’);
}
Angular JS: Creating Services…
Creating services using fatory. Factory allows us to add some logic
before creating the object we require. It allows us to pass the
function which factory then invokes and returns the result. This
allows us to return what ever we like not just call constructor of
already prepared function.
Using factory
angular.module(‘hell', []).factory(‘hellService', function () {
var hellClass = function(name) {
this.name = name; this.greet = function () {
return ‘Welcome to Hell: ' + this.name;
} } return hellClass ; });
function hellController( hellService) {
var hellSvc = new hellService(‘Cloak');
hellSvc.greet();
}
Angular JS: Creating Services…
Creating services using provider. Provider is the most configurable
of all three. All other providers are derived from it. It enables us
define how the service will be provided even before the injection
system is in place. This is achieved with configure call where we
register work during the modules configuration phase.
Using provider
var hellApp = angular.module(‘hellApp', []);
hellApp.provider(‘hell', function () {
var darkSide = true;
this.joinDarkSide = function(s){
darkSide = s;
}
var hellClass = function(name) {
this.name = name;
this.greet = function () { return ‘Welome to Hell(Dark Side):’ +
this.name; } }
….contd…
Angular JS: Creating Services…
Contd..: Using provider
var hell2Class = function(name) { this.name = name; this.greet =
function () { return ‘Welcome to Hell(Light Side) ' + this.name; } }
this.$get = function() {
if (darkSide){ return hellClass; }
else { return hell2Class; } };
});
hellApp.config(function(hellProvider){
hellProvider.joinDarkSide(false); });
function hellController( hellProvider) {
var luke = new hellProvider('Luke'); luke.greet();
}
Getting complex…?
lets see an example to
understand the concepts
better.
Angular JS: Digest

How all this works?
• AngularJS compares a value with its previous value and if it has
changed then a change event is fired. This is dirty checking.
• In AngularJS, a digest is the cycle that performs dirty checking.
This is initiated via $digest().
• If something happens outside of AngularJS, you need to let
AngularJS know to execute a digest cycle and you do that via
$apply which calls $digest.
Angular JS: Digest…

$digest();
This is the heart-beat of angular js.
It processes all of the watchers of the current scope and its
children.
The $digest()keeps calling the watchers until no more listeners are
firing. This means that it is possible to get into an infinite loop.
This function will throw 'Maximum iteration limit exceeded.' if the
number of iterations exceeds 10.
Usually, we don't call $digest() directly in controllers or
in directives. Instead, we should call $apply() (typically from
within a directives), which will force a $digest().
If you want to be notified whenever $digest() is called, you can
register a watchExpression function with $watch() with
no listener.
Angular JS: Watch Expressions

Behind every $digest cycle is a good watchExpression.
watchExpressions return the value of what is being watched on
every $digest cycle. This is the trenches of dirty checking. If the
value of the current watchExpression call and the previous
watchExpression call do not match then a listener is fired.
Syntax:
scope.$watch('name', function(newValue, oldValue)
{ /* Do something clever here */ });
Angular JS: $apply

$apply is a courier service that the outside world can recruit to tell
AngularJS that something has happened and drop off an optional
expression to be handled.
To follow the courier analogy, $apply delivers the message and
possibly a package to the sweet lady at the front desk named
$evalerie, but you can call her $eval.
Now $eval checks to make sure that $apply dropped off a
legitimate expression. If something is wrong while it is being
evaluated then an exception is thrown and passed to the
$exceptionHandler service. From there, $digest is called to kick off
the $digest cycle.
Eg.: http://jsfiddle.net/simpulton/huKHQ/
Angular JS with Java
(Springs / Struts
/ Hibernate) :
READER-APP
Reader-app : Design
The Reader App has been divided into five sub-projects: reader-util,
reader-services, reader-commons, reader-apis, reader-app.
Now lets discuss each project in details to understand the design better.
• reader-util ( Simple Java Classes )
• reader-services ( Hibernate + Springs )
• reader-commons ( POJO classes)
• reader-apis ( Spring Controllers )
• reader-app ( Angular JS + Struts + Spring )
Reader-app : Design
reader-services

reader-apis
reader-app
Okay… lets see how it looks
(running code…)
Thanks You !!!

Más contenido relacionado

La actualidad más candente

Practical AngularJS
Practical AngularJSPractical AngularJS
Practical AngularJS
Wei Ru
 
AngularJS for designers and developers
AngularJS for designers and developersAngularJS for designers and developers
AngularJS for designers and developers
Kai Koenig
 

La actualidad más candente (20)

Introduction to AngularJS
Introduction to AngularJSIntroduction to AngularJS
Introduction to AngularJS
 
Practical AngularJS
Practical AngularJSPractical AngularJS
Practical AngularJS
 
AngularJs Crash Course
AngularJs Crash CourseAngularJs Crash Course
AngularJs Crash Course
 
AngularJS Best Practices
AngularJS Best PracticesAngularJS Best Practices
AngularJS Best Practices
 
Understanding angular js
Understanding angular jsUnderstanding angular js
Understanding angular js
 
AngularJS for designers and developers
AngularJS for designers and developersAngularJS for designers and developers
AngularJS for designers and developers
 
AngularJs
AngularJsAngularJs
AngularJs
 
Angular js 1.0-fundamentals
Angular js 1.0-fundamentalsAngular js 1.0-fundamentals
Angular js 1.0-fundamentals
 
AngularJS Framework
AngularJS FrameworkAngularJS Framework
AngularJS Framework
 
Angular js PPT
Angular js PPTAngular js PPT
Angular js PPT
 
Front end development with Angular JS
Front end development with Angular JSFront end development with Angular JS
Front end development with Angular JS
 
AngularJS: an introduction
AngularJS: an introductionAngularJS: an introduction
AngularJS: an introduction
 
Angular js
Angular jsAngular js
Angular js
 
AngularJS introduction
AngularJS introductionAngularJS introduction
AngularJS introduction
 
AngularJS Project Setup step-by- step guide - RapidValue Solutions
AngularJS Project Setup step-by- step guide - RapidValue SolutionsAngularJS Project Setup step-by- step guide - RapidValue Solutions
AngularJS Project Setup step-by- step guide - RapidValue Solutions
 
Angular js
Angular jsAngular js
Angular js
 
AngularJS in 60ish Minutes
AngularJS in 60ish MinutesAngularJS in 60ish Minutes
AngularJS in 60ish Minutes
 
AngularJS - Services
AngularJS - ServicesAngularJS - Services
AngularJS - Services
 
AngularJS Beginners Workshop
AngularJS Beginners WorkshopAngularJS Beginners Workshop
AngularJS Beginners Workshop
 
Dynamic Application Development by NodeJS ,AngularJS with OrientDB
Dynamic Application Development by NodeJS ,AngularJS with OrientDBDynamic Application Development by NodeJS ,AngularJS with OrientDB
Dynamic Application Development by NodeJS ,AngularJS with OrientDB
 

Destacado

Destacado (20)

Intro to angular
Intro to angularIntro to angular
Intro to angular
 
Angular.JS - Estado Atual
Angular.JS - Estado AtualAngular.JS - Estado Atual
Angular.JS - Estado Atual
 
Angular JS blog tutorial
Angular JS blog tutorialAngular JS blog tutorial
Angular JS blog tutorial
 
Why angular js Framework
Why angular js Framework Why angular js Framework
Why angular js Framework
 
AngularJS - introduction & how it works?
AngularJS - introduction & how it works?AngularJS - introduction & how it works?
AngularJS - introduction & how it works?
 
최근 Javascript framework 조사
최근 Javascript framework 조사최근 Javascript framework 조사
최근 Javascript framework 조사
 
Spring vs. Java EE QConSP 2012
Spring vs. Java EE QConSP 2012Spring vs. Java EE QConSP 2012
Spring vs. Java EE QConSP 2012
 
Live Demo : Trending Angular JS Featues
Live Demo : Trending Angular JS FeatuesLive Demo : Trending Angular JS Featues
Live Demo : Trending Angular JS Featues
 
Building scalable applications with angular js
Building scalable applications with angular jsBuilding scalable applications with angular js
Building scalable applications with angular js
 
Angular js best practice
Angular js best practiceAngular js best practice
Angular js best practice
 
Angular JS - Develop Responsive Single Page Application
Angular JS - Develop Responsive Single Page ApplicationAngular JS - Develop Responsive Single Page Application
Angular JS - Develop Responsive Single Page Application
 
Angular 2
Angular 2Angular 2
Angular 2
 
AngularJS application architecture
AngularJS application architectureAngularJS application architecture
AngularJS application architecture
 
Microservices - java ee vs spring boot and spring cloud
Microservices - java ee vs spring boot and spring cloudMicroservices - java ee vs spring boot and spring cloud
Microservices - java ee vs spring boot and spring cloud
 
AngularJS - What is it & Why is it awesome ? (with demos)
AngularJS - What is it & Why is it awesome ? (with demos)AngularJS - What is it & Why is it awesome ? (with demos)
AngularJS - What is it & Why is it awesome ? (with demos)
 
AngularJS Basics with Example
AngularJS Basics with ExampleAngularJS Basics with Example
AngularJS Basics with Example
 
Introduction to Angular 2
Introduction to Angular 2Introduction to Angular 2
Introduction to Angular 2
 
AngularJS Architecture
AngularJS ArchitectureAngularJS Architecture
AngularJS Architecture
 
Introduction to angular 2
Introduction to angular 2Introduction to angular 2
Introduction to angular 2
 
Dynamic content with Angular
Dynamic content with AngularDynamic content with Angular
Dynamic content with Angular
 

Similar a Angular js

Angular Presentation
Angular PresentationAngular Presentation
Angular Presentation
Adam Moore
 

Similar a Angular js (20)

Angular js
Angular jsAngular js
Angular js
 
Angular workshop - Full Development Guide
Angular workshop - Full Development GuideAngular workshop - Full Development Guide
Angular workshop - Full Development Guide
 
AngularJS Basics
AngularJS BasicsAngularJS Basics
AngularJS Basics
 
Angular Js Basics
Angular Js BasicsAngular Js Basics
Angular Js Basics
 
Angular
AngularAngular
Angular
 
Angular
AngularAngular
Angular
 
Angular js
Angular jsAngular js
Angular js
 
AngularJs Workshop SDP December 28th 2014
AngularJs Workshop SDP December 28th 2014AngularJs Workshop SDP December 28th 2014
AngularJs Workshop SDP December 28th 2014
 
Angularjs Basics
Angularjs BasicsAngularjs Basics
Angularjs Basics
 
Angular Js Get Started - Complete Course
Angular Js Get Started - Complete CourseAngular Js Get Started - Complete Course
Angular Js Get Started - Complete Course
 
Introduction to single page application with angular js
Introduction to single page application with angular jsIntroduction to single page application with angular js
Introduction to single page application with angular js
 
Intoduction to Angularjs
Intoduction to AngularjsIntoduction to Angularjs
Intoduction to Angularjs
 
angularJs Workshop
angularJs WorkshopangularJs Workshop
angularJs Workshop
 
Intro to AngularJs
Intro to AngularJsIntro to AngularJs
Intro to AngularJs
 
AngularJS Workshop
AngularJS WorkshopAngularJS Workshop
AngularJS Workshop
 
AngularJs Superheroic JavaScript MVW Framework Services by Miracle Studios
AngularJs Superheroic JavaScript MVW Framework Services by Miracle StudiosAngularJs Superheroic JavaScript MVW Framework Services by Miracle Studios
AngularJs Superheroic JavaScript MVW Framework Services by Miracle Studios
 
Angular1x and Angular 2 for Beginners
Angular1x and Angular 2 for BeginnersAngular1x and Angular 2 for Beginners
Angular1x and Angular 2 for Beginners
 
AngularJS in practice
AngularJS in practiceAngularJS in practice
AngularJS in practice
 
SF Cordova Meetup
SF Cordova MeetupSF Cordova Meetup
SF Cordova Meetup
 
Angular Presentation
Angular PresentationAngular Presentation
Angular Presentation
 

Angular js

  • 1. Angular JS and Java (Spring, Struts and Hibernate) …? Hey All, I am Preetam Dwivedi
  • 2. What is “Angular JS” ? AngularJS is an open-source JavaScript framework, maintained by Google, that assists with running single-page applications. Its goal is to augment web-based applications with model–view– controller (MVC) capability, in an effort to make both development and testing easier. AngularJS allows the developer to specify custom and reusable HTML tags that moderate the behavior of certain elements these attributes are called ‘Diretives’. Example: ng-app , ng-model etc.
  • 3. Why “Angular JS” ? • Defines various ways to organize web app at client side. • Enhances HTML using various directives, attributes and templates. • Encourage 2-way data binding • Encourage MVC • Code reuse • Good for SPAs
  • 4. Angular JS: MVC View 3. Implements the business Logic on response data and bind it to view Model 1. Event or User Action or View Load Controller 2. Maps to particular model after fetching the data
  • 5. Angular JS: Core Concepts Bootstrap Data Binding Directives Expressions Filters Controllers Dependency Injection Views and Routing Services $digest
  • 6. Angular JS: Bootstrap <!doctype html> <html lang="en" ng-app> <head> <meta charset="utf-8"> <title>My HTML File</title> <script src="angular.js"></script> </head> <body> ….. </body> </html> The ng-app attribute represents an Angular directive named ngApp. The ngApp found in the document will be used to define the root element to autobootstrap as an application.
  • 7. What happens during bootstrapping..? There are 3 important things that happen during the app bootstrap: • The injector that will be used for dependency injection is created. • The injector will then create the root scope that will become the context for the model of our application. • Angular will then compile the DOM starting at the ngApp root element, processing any directives and bindings found along the way.
  • 8. Angular JS: Data Binding Data-binding in Angular web apps is the automatic synchronization of data between the model and view components. First the template (uncompiled HTML) is compiled on the browser, and second, the compilation step produces a live view.
  • 9. Angular JS: Directives I am ng-model and i am a directive. <input ng-model=“hell"> Directives are markers on a DOM element (such as an attribute, element name, or CSS class) that tell AngularJS's HTML compiler ($compile) to attach a specified behavior to that DOM element or even transform the DOM element and its children. Angular provide some in-built directives like ngApp(ngapp), ngModel(ng-model), ngIf(ng-if) etc.
  • 10. Angular JS: Directives… Do I need to get compiled…? <input ng-model=“hell"> What does it mean to "compile" an HTML template? For AngularJS, "compilation" means attaching event listeners to the HTML to make it interactive. The reason the term "compile" is used that the recursive process of attaching directives mirrors the process of compiling source code in compiled programming languages.
  • 11. Angular JS: Expressions {{ expression }} 1+2=3 {{a.b.c}} I am an expression. I use $parse service to evaluate. 1+2={{1+2}} Expression evaluation is forgiving to undefined and null. It means that if any of a/b/c is null or undefined it will not throw exception and show nothing(blank).
  • 12. Angular JS: Filters {{ 1.234 | number:2 }} I am a Filter. I will show up to 2 decimal points only i.e. 1.23 A filter formats the value of an expression for display to the user. They can be used in view templates, controllers or services and it is easy to define your own filter. {{ expression | filter }} {{ expression | filter1 | filter2 | ... }} {{ expression | filter:arg1 : arg2 ... }}
  • 13. Its too much to remember. Lets see an example.
  • 14. Angular JS: Controllers In Angular, a Controller is a JavaScript constructor function that is used to augment the Angular Scope. When a Controller is attached to the DOM via the ng-controller directive, Angular will instantiate a new Controller object, using the specified Controller's constructor function. A new child scope will be available as an injectable parameter to the Controller's constructor function as $scope. I am a controller. I contain all business logics. <div ng-controller=“hellCtrl"> {{msg}} </div> function hellCtrl($scope) { $scope.msg = ‘Hell!!!'; }
  • 15. Angular JS: Controllers… Please use me correctly. function hellCtrl($scope) { $scope.msg = ‘Hell!!!'; } Do not use Controllers for: • Any kind of DOM manipulation — Controllers should contain only business logic. • Input formatting (use angular form controls instead). • Output filtering (use angular filters instead). • Sharing stateless or stateful code across Controllers(use angular services instead). • Managing the life-cycle of other components (for example, to create service instances).
  • 16. Angular JS: Dependency Injection $scope and hellSvc are two services which need to be injected into the controller. function hellCtrl($scope, hellSvc) { ... } Dependency Injection (DI) is a software design pattern that deals with how code gets hold of its dependencies. There are only 3 ways an object or a function can get a hold of its dependencies: • The dependency can be created, using the new operator. • The dependency can be looked up by referring to a global variable. • The dependency can be passed in to where it is needed.
  • 17. Angular JS: Views and Routing Sample App Router Config var app= angular.module(‘app', [ 'ngRoute‘, ‘appCtrl’ ]); app.config(['$routeProvider', function($routeProvider) { $routeProvider.when('/home', { templateUrl: 'partials/home.html', controller: ‘homeCtrl' }).otherwise({ redirectTo: '/error’ }); }]); $route is used for deep-linking URLs to controllers and views (HTML partials). It watches $location.url() and tries to map the path to an existing route definition. Routing requires the ngRoute module to be installed. We can define routes through $routeProvider’s API.
  • 18. Angular JS: Services What are Angular Services? Angular services are singletons objects or functions that carry out specific tasks common to web apps. Angular has a number of built in services, such as the $http service. Using $inject for injection Using inline injection var ctrl= function($location) { ... }; ctrl.$inject = ['$location']; var svc= function($http) { ... }; myModule.controller(‘ctrl', ctrl); myModule.factory(‘svc', ['$http', svc]);
  • 19. Angular JS: Services and DI xTended app.config(function($provide) { $provide.factory('greeting', function() { return function(name) { alert("Hello, " + name); }; }); }); var greeting = $injector.get('greeting'); greeting(‘Cloak’);
  • 20. Angular JS: Creating Services All services are defined by using $provider service and it’s respective methods provider, factory and service. These methods are also available on the module object so you can use them without injecting $provider service. Using angular module Using $provider service var myModule = angular.module('myModule', []); myModule.factory('serviceId', function() { var inst; … return inst; }); angular.module('myModule', [], function($provide) { $provide.factory('serviceId', function() { var inst; … return inst; });});
  • 21. Angular JS: Creating Services… Creating services using service. Service is suitable for cases when you have a ready function that you need to share throughout the app without any “preprocessing”. It expects to receive a constructor which it then invokes by using new and then returns a result. Using service angular.module(‘hell', []).service(‘hellService', function(){ this.greet = function (name) { return ‘Welcome to Hell : ' + name; } }); function hellController( hellService) { hellService.greet(‘Cloak’); }
  • 22. Angular JS: Creating Services… Creating services using fatory. Factory allows us to add some logic before creating the object we require. It allows us to pass the function which factory then invokes and returns the result. This allows us to return what ever we like not just call constructor of already prepared function. Using factory angular.module(‘hell', []).factory(‘hellService', function () { var hellClass = function(name) { this.name = name; this.greet = function () { return ‘Welcome to Hell: ' + this.name; } } return hellClass ; }); function hellController( hellService) { var hellSvc = new hellService(‘Cloak'); hellSvc.greet(); }
  • 23. Angular JS: Creating Services… Creating services using provider. Provider is the most configurable of all three. All other providers are derived from it. It enables us define how the service will be provided even before the injection system is in place. This is achieved with configure call where we register work during the modules configuration phase. Using provider var hellApp = angular.module(‘hellApp', []); hellApp.provider(‘hell', function () { var darkSide = true; this.joinDarkSide = function(s){ darkSide = s; } var hellClass = function(name) { this.name = name; this.greet = function () { return ‘Welome to Hell(Dark Side):’ + this.name; } } ….contd…
  • 24. Angular JS: Creating Services… Contd..: Using provider var hell2Class = function(name) { this.name = name; this.greet = function () { return ‘Welcome to Hell(Light Side) ' + this.name; } } this.$get = function() { if (darkSide){ return hellClass; } else { return hell2Class; } }; }); hellApp.config(function(hellProvider){ hellProvider.joinDarkSide(false); }); function hellController( hellProvider) { var luke = new hellProvider('Luke'); luke.greet(); }
  • 25. Getting complex…? lets see an example to understand the concepts better.
  • 26. Angular JS: Digest How all this works? • AngularJS compares a value with its previous value and if it has changed then a change event is fired. This is dirty checking. • In AngularJS, a digest is the cycle that performs dirty checking. This is initiated via $digest(). • If something happens outside of AngularJS, you need to let AngularJS know to execute a digest cycle and you do that via $apply which calls $digest.
  • 27. Angular JS: Digest… $digest(); This is the heart-beat of angular js. It processes all of the watchers of the current scope and its children. The $digest()keeps calling the watchers until no more listeners are firing. This means that it is possible to get into an infinite loop. This function will throw 'Maximum iteration limit exceeded.' if the number of iterations exceeds 10. Usually, we don't call $digest() directly in controllers or in directives. Instead, we should call $apply() (typically from within a directives), which will force a $digest(). If you want to be notified whenever $digest() is called, you can register a watchExpression function with $watch() with no listener.
  • 28. Angular JS: Watch Expressions Behind every $digest cycle is a good watchExpression. watchExpressions return the value of what is being watched on every $digest cycle. This is the trenches of dirty checking. If the value of the current watchExpression call and the previous watchExpression call do not match then a listener is fired. Syntax: scope.$watch('name', function(newValue, oldValue) { /* Do something clever here */ });
  • 29. Angular JS: $apply $apply is a courier service that the outside world can recruit to tell AngularJS that something has happened and drop off an optional expression to be handled. To follow the courier analogy, $apply delivers the message and possibly a package to the sweet lady at the front desk named $evalerie, but you can call her $eval. Now $eval checks to make sure that $apply dropped off a legitimate expression. If something is wrong while it is being evaluated then an exception is thrown and passed to the $exceptionHandler service. From there, $digest is called to kick off the $digest cycle. Eg.: http://jsfiddle.net/simpulton/huKHQ/
  • 30. Angular JS with Java (Springs / Struts / Hibernate) : READER-APP
  • 31. Reader-app : Design The Reader App has been divided into five sub-projects: reader-util, reader-services, reader-commons, reader-apis, reader-app. Now lets discuss each project in details to understand the design better. • reader-util ( Simple Java Classes ) • reader-services ( Hibernate + Springs ) • reader-commons ( POJO classes) • reader-apis ( Spring Controllers ) • reader-app ( Angular JS + Struts + Spring )
  • 33. Okay… lets see how it looks (running code…)