SlideShare a Scribd company logo
ngMess: 
Angular JS DI
Presenter 
Dmitry Ivashutin 
Software Engineer
Dependency Injection 
High-level modules should not depend on 
low-level modules. Both should depend 
on abstractions. 
 Abstractions should not depend on details. 
Details should depend on abstractions.
DI in a Nutshell 
 create the dependency 
 look up the dependency 
 have the dependency injected
The provider
Wiki: The provider 
The $provide service is responsible for telling Angular how 
to create new injectable things; these things are 
called services. Services are defined by things 
called providers, which is what you're creating when you 
use $provide. Defining a provider is done via 
the provider method on the $provide service, and you can 
get hold of the $provide service by asking for it to be injected 
into an application's config function. 
https://github.com/angular/angular.js/wiki/Understanding-Dependency-Injection
ngMess: AngularJS Dependency Injection
How do we usually inject? 
myApp.service('alerter', function () { 
http://jsfiddle.net/ae87/9x7Aq/2/ 
this.sayHello = function(){ 
alert('Hello! '); 
} 
this.sayGoodbye = function(){ 
alert('Goodbye!'); 
} 
});
Let’s start from
Create provider at configure stage 
app.config(function ($provide) { 
$provide.provider('greeting', function () { 
this.$get = function () { 
return function (name) { 
alert('Hello, ' + name); 
}; 
}; 
}); 
});
It’s a valid way
ngMess: AngularJS Dependency Injection
There are other ways
So called “services” 
Factory Service 
Provider 
Value Constant
Calling exact the same code inside 
that we wrote above
Provider way 
function provider(name, provider_) { 
assertNotHasOwnProperty(name, 'service'); 
if (isFunction(provider_) || isArray(provider_)) { 
provider_ 
= providerInjector.instantiate(provider_); 
} 
if (!provider_.$get) 
return providerCache[name + providerSuffix] 
= provider_; 
}
Factory way 
function factory(name, factoryFn) { 
return provider( 
name, 
{ 
$get: factoryFn 
}); 
}
Service way 
function service(name, constructor) { 
return factory( 
name, 
[ 
'$injector', 
function ($injector) { 
return $injector.instantiate(constructor); 
} 
]); 
}
Value way 
function value(name, val) { 
return factory( 
name, 
valueFn(val) 
); 
} 
function valueFn(value) { 
return function () { 
return value; 
}; 
}
Constant way 
function constant(name, value) { 
assertNotHasOwnProperty(name, 'constant'); 
providerCache[name] = value; 
instanceCache[name] = value; 
}
ngMess: AngularJS Dependency Injection
Syntactic sugar
Looks annoying, right? 
app.config(function($provide) { ... })
Module level access 
$provide 
.provider('greeting', ...); 
angular 
.module('myModule', []) 
.provider('greeting', ...);
“A Sound of Thunder”
ngMess: AngularJS Dependency Injection
Service Recipe 
 Utility functions via public API 
 Non-new-able stuff 
Works better for objects of custom type 
service(class) 
– registers a constructor function, 
class that will be wrapped in 
a service provider object
Factory Recipe 
 Exposing public API 
 Constructors via new-able functions 
Can produce JavaScript primitives and functions 
factory(fn) 
– registers a service factory 
function, that will be wrapped 
in a service provider object
Provider Recipe 
 Configurable stuff 
You don't need it unless you are building a 
reusable piece of code that needs global 
configuration 
provider(provider) 
– registers a service provider 
with the $injector
Value Recipe 
 Exposing static values and constants 
value(obj) 
– registers a value/object that 
can only be accessed by 
services, not providers
Constant Recipe 
 Exposing compile time static values and 
constants 
constant(obj) 
– registers a value/object 
that can be accessed by 
providers and services
Decorator
Decorator way 
function decorator(serviceName, decorFn) { 
var origProvider = providerInjector 
.get(serviceName + providerSuffix), 
orig$get = origProvider.$get; 
origProvider.$get = function () { 
var origInstance = instanceInjector 
.invoke(orig$get, origProvider); 
return instanceInjector.invoke( 
decorFn, null, 
{ $delegate: origInstance }); 
}; 
}
Know-how 
app.config(function ($provide) { 
$provide.decorator('$log', function ($delegate) { 
// save the original function 
var _log = $delegate.log; 
// replace the original behavior 
$delegate.log = function (msg) { 
_log(msg); 
alert(msg); 
}; 
return $delegate; 
}); 
}); 
http://plnkr.co/edit/imqmvUfk4oWWuwg75sP1?p=preview
ngMess: AngularJS Dependency Injection
Few more quick facts
Injector: Why 
 Feel the power of DI 
 Control the injection real-time 
 Access DI container from outside of your app 
 Primary usage - testing
Injector: How 
function MyController($scope, $injector) { 
$scope.doSomething = function(someServiceName) { 
// someService contains the name of a service 
var service = $injector.get(someServiceName); 
service.do(); 
}; 
}
Scripts require proper order
The End! Questions?

More Related Content

PPT
Building Robust jQuery Plugins
PDF
Paying off technical debt with PHPSpec
PPTX
AngularJs $provide API internals & circular dependency problem.
PPTX
AngularJS $Provide Service
PPTX
Upgrading from Angular 1.x to Angular 2.x
PDF
Frontin like-a-backer
PPTX
Template syntax in Angular 2.0
PPTX
Forms in AngularJS
Building Robust jQuery Plugins
Paying off technical debt with PHPSpec
AngularJs $provide API internals & circular dependency problem.
AngularJS $Provide Service
Upgrading from Angular 1.x to Angular 2.x
Frontin like-a-backer
Template syntax in Angular 2.0
Forms in AngularJS

What's hot (20)

PDF
Cyclejs introduction
PPTX
Routing And Navigation
PPTX
Workshop 1: Good practices in JavaScript
PPTX
Modules and injector
PPT
jQuery Plugin
PPTX
AngularJS in practice
PPTX
Angular 1.x vs. Angular 2.x
PPTX
Http Communication in Angular 2.0
PDF
Workshop 5: JavaScript testing
PDF
JavaScript Promises
PDF
Java Script Best Practices
PPTX
Angular 2 Architecture
PPTX
AngularJS Animations
PPTX
React native tour
PDF
Rails is not just Ruby
PPT
Advanced JavaScript
PDF
Workshop 10: ECMAScript 6
PDF
Excellent
PDF
How I started to love design patterns
Cyclejs introduction
Routing And Navigation
Workshop 1: Good practices in JavaScript
Modules and injector
jQuery Plugin
AngularJS in practice
Angular 1.x vs. Angular 2.x
Http Communication in Angular 2.0
Workshop 5: JavaScript testing
JavaScript Promises
Java Script Best Practices
Angular 2 Architecture
AngularJS Animations
React native tour
Rails is not just Ruby
Advanced JavaScript
Workshop 10: ECMAScript 6
Excellent
How I started to love design patterns
Ad

Viewers also liked (6)

PDF
AngularJS - dependency injection
PPT
introduction to Angularjs basics
PPT
Dynamic Application Development by NodeJS ,AngularJS with OrientDB
PPTX
AngularJS intro
PDF
Gettings started with the superheroic JavaScript library AngularJS
PDF
Dependency Injection @ AngularJS
AngularJS - dependency injection
introduction to Angularjs basics
Dynamic Application Development by NodeJS ,AngularJS with OrientDB
AngularJS intro
Gettings started with the superheroic JavaScript library AngularJS
Dependency Injection @ AngularJS
Ad

Similar to ngMess: AngularJS Dependency Injection (20)

PPTX
AngularJs-training
PDF
Technozaure - Angular2
PDF
WordPress Realtime - WordCamp São Paulo 2015
PDF
Angular.js Primer in Aalto University
PPTX
Getting the Most Out of jQuery Widgets
PDF
ChtiJUG - Introduction à Angular2
PDF
Explaination of angular
PPTX
How to perform debounce in react
PDF
"Angular.js Concepts in Depth" by Aleksandar Simović
ODP
AngularJs Crash Course
PDF
Get AngularJS Started!
PPTX
Building an End-to-End AngularJS Application
PDF
A resource oriented framework using the DI/AOP/REST triangle
PDF
Doctrine For Beginners
PDF
Complex Sites with Silex
PDF
ZF2 for the ZF1 Developer
PDF
Workshop 13: AngularJS Parte II
PDF
Into the ZF2 Service Manager
PDF
2018 05-16 Evolving Technologies: React, Babel & Webpack
PDF
Restaurant Server - Transcript.pdf
AngularJs-training
Technozaure - Angular2
WordPress Realtime - WordCamp São Paulo 2015
Angular.js Primer in Aalto University
Getting the Most Out of jQuery Widgets
ChtiJUG - Introduction à Angular2
Explaination of angular
How to perform debounce in react
"Angular.js Concepts in Depth" by Aleksandar Simović
AngularJs Crash Course
Get AngularJS Started!
Building an End-to-End AngularJS Application
A resource oriented framework using the DI/AOP/REST triangle
Doctrine For Beginners
Complex Sites with Silex
ZF2 for the ZF1 Developer
Workshop 13: AngularJS Parte II
Into the ZF2 Service Manager
2018 05-16 Evolving Technologies: React, Babel & Webpack
Restaurant Server - Transcript.pdf

Recently uploaded (20)

PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Encapsulation theory and applications.pdf
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
Empathic Computing: Creating Shared Understanding
PDF
CIFDAQ's Market Insight: SEC Turns Pro Crypto
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Electronic commerce courselecture one. Pdf
PDF
KodekX | Application Modernization Development
PPTX
Big Data Technologies - Introduction.pptx
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PPT
Teaching material agriculture food technology
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
NewMind AI Weekly Chronicles - August'25 Week I
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Encapsulation theory and applications.pdf
Mobile App Security Testing_ A Comprehensive Guide.pdf
Understanding_Digital_Forensics_Presentation.pptx
Empathic Computing: Creating Shared Understanding
CIFDAQ's Market Insight: SEC Turns Pro Crypto
Chapter 3 Spatial Domain Image Processing.pdf
Electronic commerce courselecture one. Pdf
KodekX | Application Modernization Development
Big Data Technologies - Introduction.pptx
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Diabetes mellitus diagnosis method based random forest with bat algorithm
Advanced methodologies resolving dimensionality complications for autism neur...
MYSQL Presentation for SQL database connectivity
Per capita expenditure prediction using model stacking based on satellite ima...
Teaching material agriculture food technology
Reach Out and Touch Someone: Haptics and Empathic Computing
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
NewMind AI Weekly Chronicles - August'25 Week I

ngMess: AngularJS Dependency Injection

  • 2. Presenter Dmitry Ivashutin Software Engineer
  • 3. Dependency Injection High-level modules should not depend on low-level modules. Both should depend on abstractions.  Abstractions should not depend on details. Details should depend on abstractions.
  • 4. DI in a Nutshell  create the dependency  look up the dependency  have the dependency injected
  • 6. Wiki: The provider The $provide service is responsible for telling Angular how to create new injectable things; these things are called services. Services are defined by things called providers, which is what you're creating when you use $provide. Defining a provider is done via the provider method on the $provide service, and you can get hold of the $provide service by asking for it to be injected into an application's config function. https://github.com/angular/angular.js/wiki/Understanding-Dependency-Injection
  • 8. How do we usually inject? myApp.service('alerter', function () { http://jsfiddle.net/ae87/9x7Aq/2/ this.sayHello = function(){ alert('Hello! '); } this.sayGoodbye = function(){ alert('Goodbye!'); } });
  • 10. Create provider at configure stage app.config(function ($provide) { $provide.provider('greeting', function () { this.$get = function () { return function (name) { alert('Hello, ' + name); }; }; }); });
  • 14. So called “services” Factory Service Provider Value Constant
  • 15. Calling exact the same code inside that we wrote above
  • 16. Provider way function provider(name, provider_) { assertNotHasOwnProperty(name, 'service'); if (isFunction(provider_) || isArray(provider_)) { provider_ = providerInjector.instantiate(provider_); } if (!provider_.$get) return providerCache[name + providerSuffix] = provider_; }
  • 17. Factory way function factory(name, factoryFn) { return provider( name, { $get: factoryFn }); }
  • 18. Service way function service(name, constructor) { return factory( name, [ '$injector', function ($injector) { return $injector.instantiate(constructor); } ]); }
  • 19. Value way function value(name, val) { return factory( name, valueFn(val) ); } function valueFn(value) { return function () { return value; }; }
  • 20. Constant way function constant(name, value) { assertNotHasOwnProperty(name, 'constant'); providerCache[name] = value; instanceCache[name] = value; }
  • 23. Looks annoying, right? app.config(function($provide) { ... })
  • 24. Module level access $provide .provider('greeting', ...); angular .module('myModule', []) .provider('greeting', ...);
  • 25. “A Sound of Thunder”
  • 27. Service Recipe  Utility functions via public API  Non-new-able stuff Works better for objects of custom type service(class) – registers a constructor function, class that will be wrapped in a service provider object
  • 28. Factory Recipe  Exposing public API  Constructors via new-able functions Can produce JavaScript primitives and functions factory(fn) – registers a service factory function, that will be wrapped in a service provider object
  • 29. Provider Recipe  Configurable stuff You don't need it unless you are building a reusable piece of code that needs global configuration provider(provider) – registers a service provider with the $injector
  • 30. Value Recipe  Exposing static values and constants value(obj) – registers a value/object that can only be accessed by services, not providers
  • 31. Constant Recipe  Exposing compile time static values and constants constant(obj) – registers a value/object that can be accessed by providers and services
  • 33. Decorator way function decorator(serviceName, decorFn) { var origProvider = providerInjector .get(serviceName + providerSuffix), orig$get = origProvider.$get; origProvider.$get = function () { var origInstance = instanceInjector .invoke(orig$get, origProvider); return instanceInjector.invoke( decorFn, null, { $delegate: origInstance }); }; }
  • 34. Know-how app.config(function ($provide) { $provide.decorator('$log', function ($delegate) { // save the original function var _log = $delegate.log; // replace the original behavior $delegate.log = function (msg) { _log(msg); alert(msg); }; return $delegate; }); }); http://plnkr.co/edit/imqmvUfk4oWWuwg75sP1?p=preview
  • 36. Few more quick facts
  • 37. Injector: Why  Feel the power of DI  Control the injection real-time  Access DI container from outside of your app  Primary usage - testing
  • 38. Injector: How function MyController($scope, $injector) { $scope.doSomething = function(someServiceName) { // someService contains the name of a service var service = $injector.get(someServiceName); service.do(); }; }