"Angular.js Concepts in Depth" by Aleksandar Simović

JS Belgrade
JS BelgradeJS Belgrade
Angular.js Concepts in Depth
(we need to go deeper)
Brief overview
Quick intro (~2 min)
Core concepts:
- Modules
- DI
- Controllers
- Scopes
- Views
- Directives
- Templates
- Filters
- Providers
Change detection
Note: (lns are based on Angular 1.4.0-rc.0)
quick intro
(in case living under a rock)
- “JAVA script” client side framework
(they call it like that when they contact you from an HR agency)
- Imposes MVW architecture
- Component based
- DI
module
- Logical containers
- Module -> [controllers, filters, directives, services, factories, animations, configs]
Example:
angular.module('yourApp', ['yourDependency']);
its phases - or blocks:
- config
(define your app configuration, e.g. routes, only providers & constants)
- run
(similar to a main method, not needed but sometimes useful, only instances & constants)
DI
- each app has one $injector
- $injector can instantiate types, invoke
methods, load modules
- instance cache + instance factory
- credited with making all providers singletons
- $injector.get()
-> if inCache() return from cache
-> else instantiate
a small DI usage example :
yourApp.controller('yourCtrl', function($scope) {});
controller
- more like view models, less like controllers
- controller ~ view relation: 1-1
- can be used in relation 1-m (not the usual practice)
- each controller has its own scope and view which
contains what is shown
- created by ~ $controllerProvider
(lns 8645 - 8791)
scopes
- objects containing view related functions and properties
- each controller has one
- app has one “parent” scope ~ $rootScope
- children can have their own children
views
At the beginning (0.x ~ 1.x) there were only classic,
because the ng team thought directives could be used as
composite views with state
- classic views: ng-route
- kinda composite: ng-include
- composite views: ui-router
templates
~ an HTML fragment
~ partial view
- mostly used by directives
expressions
- code placed in “{{ }}” handlebars represent expressions
example:
<div>{{ 3+5 }}</div>
- before rendering the actual template, its expressions
are compiled by $interpolate service
- detrimental to performance
- always check their performance with batarang
- one time binding “::” (!= one-way data binding)
(lns 10485 - 10584)
directives
- composable components
- can have their own scope
- they are not providers, as they are more of an extension
to the DOM elements, but they do have their
$compileProvider (lns 5924 - 8518)
- can have its own controller
(one of the reasons why in the first Angular versions there was no need for composite view)
DDO
yourModule.directive('directiveName', function factory(injectables) {
var directiveDefinitionObject = {
priority: 0,
template: '<div></div>', // or // function(tElement, tAttrs) { ... },
// or
// templateUrl: 'directive.html', // or // function(tElement, tAttrs) { ... },
transclude: false,
restrict: 'A',
replace: true,
templateNamespace: 'html',
scope: false,
controller: function($scope, $element, $attrs, $transclude, otherInjectables) { /**...*/ },
controllerAs: 'stringIdentifier',
bindToController: false,
require: 'siblingDirectiveName', // or // ['^parentDirectiveName', '?optionalDirectiveName', '?
^optionalParent'],
compile: function compile(tElement, tAttrs, transclude) {
return {
pre: function preLink(scope, iElement, iAttrs, controller) { /**...*/ },
post: function postLink(scope, iElement, iAttrs, controller) { /**...*/ }
};
// or
// return function postLink( ... ) { ... }
}
// or
// link: {
// pre: function preLink(scope, iElement, iAttrs, controller) { ... },
// post: function postLink(scope, iElement, iAttrs, controller) { ... }
// }
// or
// link: function postLink( ... ) { ... }
};
return directiveDefinitionObject;
});
directive intrinsics
phases
- compile
- preLink
- postLink
- link
directive source example
/**
* @question
* Guess which element does this native directive extend?
*/
var htmlAnchorDirective = valueFn({
restrict: 'E',
compile: function(element, attr) {
if (!attr.href && !attr.xlinkHref) {
return function(scope, element) {
// If the linked element is not an anchor tag anymore, do nothing
if (element[0].nodeName.toLowerCase() !== 'a') return;
// SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute.
var href = toString.call(element.prop('href')) === '[object SVGAnimatedString]' ?
'xlink:href' : 'href';
element.on('click', function(event) {
// if we have no href url, then don't navigate anywhere.
if (!element.attr(href)) {
event.preventDefault();
}
});
};
}
}
});
directives
most usable ones:
- model
- event (ng-click, ng-mouseover...)
- value
- bind
- class
- include
- repeat
- show
- switch
the main list is within lns 18928 - 27672
filters
- think of it as a formatter
- an ng service used for formatting data to the user
- example
{{ expression | filter_name[:parameter_value] ... ] }}
- when registering them, Angular automatically adds
“Filter” postfix to them, in order not to mix them with
other services
- all filters are handled by their own provider ~
$FilterProvider
(lns 17663 - 18926)
filters
native filter list:
- currency
- date
- filter
- json
- limitTo
- lowercase
- number
- orderBy
- uppercase
providers
- referred to as “services” (op term)
- Represent the state of your app
- List of providers:
provider
constant
factory
service
decorator
value
(lns 4170 - 4402)
provider
- Configurable factory
- Meaning it has configuration options and a creation
function ($get)
- Can be used during the config phase
- // angular.provider('providerName');
provider source
function provider(name, provider_) {
assertNotHasOwnProperty(name, 'service');
if (isFunction(provider_) || isArray(provider_)) {
provider_ = providerInjector.instantiate(provider_);
}
if (!provider_.$get) {
throw $injectorMinErr('pget', "Provider '{0}' must define $get factory method.",
name);
}
return providerCache[name + providerSuffix] = provider_;
}
provider examples
someModule.provider('providerName', function (){
var trackingUrl = '/track';
// A provider method for configuring where the tracked events should been saved
this.setTrackingUrl = function(url) {
trackingUrl = url;
};
// The service factory function
this.$get = ['$http', function($http) {
var trackedEvents = {};
return {
// Call this to track an event
event: function(event) {
var count = trackedEvents[event] || 0;
count += 1;
trackedEvents[event] = count;
return count;
},
// Call this to save the tracked events to the trackingUrl
save: function() {
$http.post(trackingUrl, trackedEvents);
}
};
}];
});
factory
- well known
- most widely used
- private functions
- provider with a $get function
- // angular.factory('someFactory', factoryObject)
factory source
function factory(name, factoryFn, enforce) {
return provider(name, {
$get: enforce !== false ? enforceReturnValue(name, factoryFn) : factoryFn
});
}
function enforceReturnValue(name, factory) {
return function enforcedReturnValue() {
var result = instanceInjector.invoke(factory, this);
if (isUndefined(result)) {
throw $injectorMinErr('undef', "Provider '{0}' must return a value from $get
factory method.", name);
}
return result;
};
}
factory examples
someModule.factory('ping', ['$http', function($http) {
return {
ping: function {
return $http.send('/ping');
};
}]);
someModule.controller('Ctrl', ['ping', function(ping) {
ping();
}]);
someModule.factory('ping', ['$http', function($http) {
return function ping() {
return $http.send('/ping');
};
}]);
someModule.controller('Ctrl', ['ping', function(ping) {
ping();
}]);
constant
- we all know what constant means
- can’t be decorated (not shit, Sherlock)
- injectable during config phase
- Example:
angular.constant('someConstantName',
constantValue)
constant source
function constant(name, value) {
assertNotHasOwnProperty(name, 'constant');
providerCache[name] = value;
instanceCache[name] = value;
}
constant – examples
someModule.constant('SHARD_HEIGHT', 306);
someModule.constant('MY_COLOURS', ['red', 'blue', 'grey']);
value
- can not be injected in the config phase
- represents an angular variable that can be injected and used
throughout your providers, directives, controllers
example:
angular.value('someValue', actualValue)
value source
function value(name, val) {
return factory(name, valueFn(val), false);
}
service
- known but not so widespread
- injectable constructor
example:
angular.service('ServiceName', serviceObj);
service source
function service(name, constructor) {
return factory(name, ['$injector', function($injector) {
return $injector.instantiate(constructor);
}]);
}
service examples
var ServiceName = function($http) {
this.$http = $http;
};
ServiceName.$inject = ['$http'];
ServiceName.prototype.send = function() {
return this.$http.get('/some-http-address');
};
$provide.service('ServiceName', ServiceName);
angular.service('ServiceName', function($http){
this.$http = $http;
this.send = function() {
return this.$http.get('/some-http-address');
};
});
decorator
- Service instantiation interceptor
- Behavior override
- Modify / encapsulate other providers
- Can decorate every provider, except constant
- Less known, barely used
- why?
- angular-mocks uses it to add flush() to $timeout
angular.decorator('someDecorator', decoratorObj);
decorator source
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});
};
}
decorator example
/**
* @description
*
* Here we decorate the ns.$log service to convert warnings to errors
*/
angular.decorator('$log', ['$delegate', function ($delegate) {
delegate.warn = delegate.error;
return delegate;
}]);
Change detection
- dirty checking
- consists of running equality checks over all
of the data that the view depends on
Questions
(answers not promised)
1 of 37

Recommended

Angular In Depth by
Angular In DepthAngular In Depth
Angular In DepthMindfire Solutions
655 views17 slides
AngularJS - dependency injection by
AngularJS - dependency injectionAngularJS - dependency injection
AngularJS - dependency injectionAlexe Bogdan
1.5K views24 slides
Workshop 13: AngularJS Parte II by
Workshop 13: AngularJS Parte IIWorkshop 13: AngularJS Parte II
Workshop 13: AngularJS Parte IIVisual Engineering
856 views78 slides
AngularJs $provide API internals & circular dependency problem. by
AngularJs $provide API internals & circular dependency problem.AngularJs $provide API internals & circular dependency problem.
AngularJs $provide API internals & circular dependency problem.Yan Yankowski
3.2K views18 slides
AngularJs-training by
AngularJs-trainingAngularJs-training
AngularJs-trainingPratchaya Suputsopon
338 views41 slides
Angular js by
Angular jsAngular js
Angular jsBehind D Walls
2K views34 slides

More Related Content

What's hot

Workshop 17: EmberJS parte II by
Workshop 17: EmberJS parte IIWorkshop 17: EmberJS parte II
Workshop 17: EmberJS parte IIVisual Engineering
856 views54 slides
Dependency Injection @ AngularJS by
Dependency Injection @ AngularJSDependency Injection @ AngularJS
Dependency Injection @ AngularJSRan Mizrahi
4.3K views32 slides
Explaination of angular by
Explaination of angularExplaination of angular
Explaination of angularKan-Han (John) Lu
1.1K views27 slides
Solid angular by
Solid angularSolid angular
Solid angularNir Kaufman
5.2K views56 slides
Workshop 14: AngularJS Parte III by
Workshop 14: AngularJS Parte IIIWorkshop 14: AngularJS Parte III
Workshop 14: AngularJS Parte IIIVisual Engineering
759 views54 slides
Workshop 19: ReactJS Introduction by
Workshop 19: ReactJS IntroductionWorkshop 19: ReactJS Introduction
Workshop 19: ReactJS IntroductionVisual Engineering
1.7K views27 slides

What's hot(20)

Dependency Injection @ AngularJS by Ran Mizrahi
Dependency Injection @ AngularJSDependency Injection @ AngularJS
Dependency Injection @ AngularJS
Ran Mizrahi4.3K views
Solid angular by Nir Kaufman
Solid angularSolid angular
Solid angular
Nir Kaufman5.2K views
Custom AngularJS Directives by yprodev
Custom AngularJS DirectivesCustom AngularJS Directives
Custom AngularJS Directives
yprodev283 views
Opinionated AngularJS by prabhutech
Opinionated AngularJSOpinionated AngularJS
Opinionated AngularJS
prabhutech1K views
Workshop 23: ReactJS, React & Redux testing by Visual Engineering
Workshop 23: ReactJS, React & Redux testingWorkshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testing
Visual Engineering1.8K views
Workshop 26: React Native - The Native Side by Visual Engineering
Workshop 26: React Native - The Native SideWorkshop 26: React Native - The Native Side
Workshop 26: React Native - The Native Side
Visual Engineering2.8K views
Angular custom directives by Alexe Bogdan
Angular custom directivesAngular custom directives
Angular custom directives
Alexe Bogdan1.6K views
The state of hooking into Drupal - DrupalCon Dublin by Nida Ismail Shah
The state of hooking into Drupal - DrupalCon DublinThe state of hooking into Drupal - DrupalCon Dublin
The state of hooking into Drupal - DrupalCon Dublin
Nida Ismail Shah271 views
Workshop 20: ReactJS Part II Flux Pattern & Redux by Visual Engineering
Workshop 20: ReactJS Part II Flux Pattern & ReduxWorkshop 20: ReactJS Part II Flux Pattern & Redux
Workshop 20: ReactJS Part II Flux Pattern & Redux
Visual Engineering1.2K views
Events: The Object Oriented Hook System. by Nida Ismail Shah
Events: The Object Oriented Hook System.Events: The Object Oriented Hook System.
Events: The Object Oriented Hook System.
Nida Ismail Shah232 views

Similar to "Angular.js Concepts in Depth" by Aleksandar Simović

AngularJs Crash Course by
AngularJs Crash CourseAngularJs Crash Course
AngularJs Crash CourseKeith Bloomfield
9.8K views53 slides
AngularJS Architecture by
AngularJS ArchitectureAngularJS Architecture
AngularJS ArchitectureEyal Vardi
64.9K views38 slides
Introduction to angular js by
Introduction to angular jsIntroduction to angular js
Introduction to angular jsMarco Vito Moscaritolo
1.1K views32 slides
Modules and injector by
Modules and injectorModules and injector
Modules and injectorEyal Vardi
7.7K views21 slides
How and why i roll my own node.js framework by
How and why i roll my own node.js frameworkHow and why i roll my own node.js framework
How and why i roll my own node.js frameworkBen Lin
3.3K views62 slides
Symfony2 from the Trenches by
Symfony2 from the TrenchesSymfony2 from the Trenches
Symfony2 from the TrenchesJonathan Wage
5.4K views40 slides

Similar to "Angular.js Concepts in Depth" by Aleksandar Simović(20)

AngularJS Architecture by Eyal Vardi
AngularJS ArchitectureAngularJS Architecture
AngularJS Architecture
Eyal Vardi64.9K views
Modules and injector by Eyal Vardi
Modules and injectorModules and injector
Modules and injector
Eyal Vardi7.7K views
How and why i roll my own node.js framework by Ben Lin
How and why i roll my own node.js frameworkHow and why i roll my own node.js framework
How and why i roll my own node.js framework
Ben Lin3.3K views
Symfony2 from the Trenches by Jonathan Wage
Symfony2 from the TrenchesSymfony2 from the Trenches
Symfony2 from the Trenches
Jonathan Wage5.4K views
Zend Framework 2 - Basic Components by Mateusz Tymek
Zend Framework 2  - Basic ComponentsZend Framework 2  - Basic Components
Zend Framework 2 - Basic Components
Mateusz Tymek5K views
Angular presentation by Matus Szabo
Angular presentationAngular presentation
Angular presentation
Matus Szabo325 views
Symfony2 - from the trenches by Lukas Smith
Symfony2 - from the trenchesSymfony2 - from the trenches
Symfony2 - from the trenches
Lukas Smith3.3K views
ZF2 for the ZF1 Developer by Gary Hockin
ZF2 for the ZF1 DeveloperZF2 for the ZF1 Developer
ZF2 for the ZF1 Developer
Gary Hockin3.3K views
Optimizing Angular Performance in Enterprise Single Page Apps by Morgan Stone
Optimizing Angular Performance in Enterprise Single Page AppsOptimizing Angular Performance in Enterprise Single Page Apps
Optimizing Angular Performance in Enterprise Single Page Apps
Morgan Stone712 views
Dependency Injection pattern in Angular by Alexe Bogdan
Dependency Injection pattern in AngularDependency Injection pattern in Angular
Dependency Injection pattern in Angular
Alexe Bogdan1K views
Building an End-to-End AngularJS Application by Dan Wahlin
Building an End-to-End AngularJS ApplicationBuilding an End-to-End AngularJS Application
Building an End-to-End AngularJS Application
Dan Wahlin11.9K views
First Steps in Drupal Code Driven Development by Nuvole
First Steps in Drupal Code Driven DevelopmentFirst Steps in Drupal Code Driven Development
First Steps in Drupal Code Driven Development
Nuvole7.5K views
Patterns Are Good For Managers by AgileThought
Patterns Are Good For ManagersPatterns Are Good For Managers
Patterns Are Good For Managers
AgileThought957 views
AngularJs Workshop SDP December 28th 2014 by Ran Wahle
AngularJs Workshop SDP December 28th 2014AngularJs Workshop SDP December 28th 2014
AngularJs Workshop SDP December 28th 2014
Ran Wahle510 views

Recently uploaded

Copilot Prompting Toolkit_All Resources.pdf by
Copilot Prompting Toolkit_All Resources.pdfCopilot Prompting Toolkit_All Resources.pdf
Copilot Prompting Toolkit_All Resources.pdfRiccardo Zamana
11 views4 slides
Introduction to Git Source Control by
Introduction to Git Source ControlIntroduction to Git Source Control
Introduction to Git Source ControlJohn Valentino
5 views18 slides
EV Charging App Case by
EV Charging App Case EV Charging App Case
EV Charging App Case iCoderz Solutions
8 views1 slide
FOSSLight Community Day 2023-11-30 by
FOSSLight Community Day 2023-11-30FOSSLight Community Day 2023-11-30
FOSSLight Community Day 2023-11-30Shane Coughlan
5 views18 slides
Sprint 226 by
Sprint 226Sprint 226
Sprint 226ManageIQ
8 views18 slides
Dapr Unleashed: Accelerating Microservice Development by
Dapr Unleashed: Accelerating Microservice DevelopmentDapr Unleashed: Accelerating Microservice Development
Dapr Unleashed: Accelerating Microservice DevelopmentMiroslav Janeski
12 views29 slides

Recently uploaded(20)

Copilot Prompting Toolkit_All Resources.pdf by Riccardo Zamana
Copilot Prompting Toolkit_All Resources.pdfCopilot Prompting Toolkit_All Resources.pdf
Copilot Prompting Toolkit_All Resources.pdf
Riccardo Zamana11 views
Introduction to Git Source Control by John Valentino
Introduction to Git Source ControlIntroduction to Git Source Control
Introduction to Git Source Control
John Valentino5 views
FOSSLight Community Day 2023-11-30 by Shane Coughlan
FOSSLight Community Day 2023-11-30FOSSLight Community Day 2023-11-30
FOSSLight Community Day 2023-11-30
Shane Coughlan5 views
Sprint 226 by ManageIQ
Sprint 226Sprint 226
Sprint 226
ManageIQ8 views
Dapr Unleashed: Accelerating Microservice Development by Miroslav Janeski
Dapr Unleashed: Accelerating Microservice DevelopmentDapr Unleashed: Accelerating Microservice Development
Dapr Unleashed: Accelerating Microservice Development
Miroslav Janeski12 views
Dev-HRE-Ops - Addressing the _Last Mile DevOps Challenge_ in Highly Regulated... by TomHalpin9
Dev-HRE-Ops - Addressing the _Last Mile DevOps Challenge_ in Highly Regulated...Dev-HRE-Ops - Addressing the _Last Mile DevOps Challenge_ in Highly Regulated...
Dev-HRE-Ops - Addressing the _Last Mile DevOps Challenge_ in Highly Regulated...
TomHalpin96 views
How Workforce Management Software Empowers SMEs | TraQSuite by TraQSuite
How Workforce Management Software Empowers SMEs | TraQSuiteHow Workforce Management Software Empowers SMEs | TraQSuite
How Workforce Management Software Empowers SMEs | TraQSuite
TraQSuite5 views
2023-November-Schneider Electric-Meetup-BCN Admin Group.pptx by animuscrm
2023-November-Schneider Electric-Meetup-BCN Admin Group.pptx2023-November-Schneider Electric-Meetup-BCN Admin Group.pptx
2023-November-Schneider Electric-Meetup-BCN Admin Group.pptx
animuscrm15 views
Dev-Cloud Conference 2023 - Continuous Deployment Showdown: Traditionelles CI... by Marc Müller
Dev-Cloud Conference 2023 - Continuous Deployment Showdown: Traditionelles CI...Dev-Cloud Conference 2023 - Continuous Deployment Showdown: Traditionelles CI...
Dev-Cloud Conference 2023 - Continuous Deployment Showdown: Traditionelles CI...
Marc Müller42 views
Understanding HTML terminology by artembondar5
Understanding HTML terminologyUnderstanding HTML terminology
Understanding HTML terminology
artembondar56 views
AI and Ml presentation .pptx by FayazAli87
AI and Ml presentation .pptxAI and Ml presentation .pptx
AI and Ml presentation .pptx
FayazAli8712 views
Generic or specific? Making sensible software design decisions by Bert Jan Schrijver
Generic or specific? Making sensible software design decisionsGeneric or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisions
Fleet Management Software in India by Fleetable
Fleet Management Software in India Fleet Management Software in India
Fleet Management Software in India
Fleetable12 views

"Angular.js Concepts in Depth" by Aleksandar Simović

  • 1. Angular.js Concepts in Depth (we need to go deeper)
  • 2. Brief overview Quick intro (~2 min) Core concepts: - Modules - DI - Controllers - Scopes - Views - Directives - Templates - Filters - Providers Change detection Note: (lns are based on Angular 1.4.0-rc.0)
  • 3. quick intro (in case living under a rock) - “JAVA script” client side framework (they call it like that when they contact you from an HR agency) - Imposes MVW architecture - Component based - DI
  • 4. module - Logical containers - Module -> [controllers, filters, directives, services, factories, animations, configs] Example: angular.module('yourApp', ['yourDependency']); its phases - or blocks: - config (define your app configuration, e.g. routes, only providers & constants) - run (similar to a main method, not needed but sometimes useful, only instances & constants)
  • 5. DI - each app has one $injector - $injector can instantiate types, invoke methods, load modules - instance cache + instance factory - credited with making all providers singletons - $injector.get() -> if inCache() return from cache -> else instantiate a small DI usage example : yourApp.controller('yourCtrl', function($scope) {});
  • 6. controller - more like view models, less like controllers - controller ~ view relation: 1-1 - can be used in relation 1-m (not the usual practice) - each controller has its own scope and view which contains what is shown - created by ~ $controllerProvider (lns 8645 - 8791)
  • 7. scopes - objects containing view related functions and properties - each controller has one - app has one “parent” scope ~ $rootScope - children can have their own children
  • 8. views At the beginning (0.x ~ 1.x) there were only classic, because the ng team thought directives could be used as composite views with state - classic views: ng-route - kinda composite: ng-include - composite views: ui-router
  • 9. templates ~ an HTML fragment ~ partial view - mostly used by directives
  • 10. expressions - code placed in “{{ }}” handlebars represent expressions example: <div>{{ 3+5 }}</div> - before rendering the actual template, its expressions are compiled by $interpolate service - detrimental to performance - always check their performance with batarang - one time binding “::” (!= one-way data binding) (lns 10485 - 10584)
  • 11. directives - composable components - can have their own scope - they are not providers, as they are more of an extension to the DOM elements, but they do have their $compileProvider (lns 5924 - 8518) - can have its own controller (one of the reasons why in the first Angular versions there was no need for composite view)
  • 12. DDO yourModule.directive('directiveName', function factory(injectables) { var directiveDefinitionObject = { priority: 0, template: '<div></div>', // or // function(tElement, tAttrs) { ... }, // or // templateUrl: 'directive.html', // or // function(tElement, tAttrs) { ... }, transclude: false, restrict: 'A', replace: true, templateNamespace: 'html', scope: false, controller: function($scope, $element, $attrs, $transclude, otherInjectables) { /**...*/ }, controllerAs: 'stringIdentifier', bindToController: false, require: 'siblingDirectiveName', // or // ['^parentDirectiveName', '?optionalDirectiveName', '? ^optionalParent'], compile: function compile(tElement, tAttrs, transclude) { return { pre: function preLink(scope, iElement, iAttrs, controller) { /**...*/ }, post: function postLink(scope, iElement, iAttrs, controller) { /**...*/ } }; // or // return function postLink( ... ) { ... } } // or // link: { // pre: function preLink(scope, iElement, iAttrs, controller) { ... }, // post: function postLink(scope, iElement, iAttrs, controller) { ... } // } // or // link: function postLink( ... ) { ... } }; return directiveDefinitionObject; });
  • 13. directive intrinsics phases - compile - preLink - postLink - link
  • 14. directive source example /** * @question * Guess which element does this native directive extend? */ var htmlAnchorDirective = valueFn({ restrict: 'E', compile: function(element, attr) { if (!attr.href && !attr.xlinkHref) { return function(scope, element) { // If the linked element is not an anchor tag anymore, do nothing if (element[0].nodeName.toLowerCase() !== 'a') return; // SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute. var href = toString.call(element.prop('href')) === '[object SVGAnimatedString]' ? 'xlink:href' : 'href'; element.on('click', function(event) { // if we have no href url, then don't navigate anywhere. if (!element.attr(href)) { event.preventDefault(); } }); }; } } });
  • 15. directives most usable ones: - model - event (ng-click, ng-mouseover...) - value - bind - class - include - repeat - show - switch the main list is within lns 18928 - 27672
  • 16. filters - think of it as a formatter - an ng service used for formatting data to the user - example {{ expression | filter_name[:parameter_value] ... ] }} - when registering them, Angular automatically adds “Filter” postfix to them, in order not to mix them with other services - all filters are handled by their own provider ~ $FilterProvider (lns 17663 - 18926)
  • 17. filters native filter list: - currency - date - filter - json - limitTo - lowercase - number - orderBy - uppercase
  • 18. providers - referred to as “services” (op term) - Represent the state of your app - List of providers: provider constant factory service decorator value (lns 4170 - 4402)
  • 19. provider - Configurable factory - Meaning it has configuration options and a creation function ($get) - Can be used during the config phase - // angular.provider('providerName');
  • 20. provider source function provider(name, provider_) { assertNotHasOwnProperty(name, 'service'); if (isFunction(provider_) || isArray(provider_)) { provider_ = providerInjector.instantiate(provider_); } if (!provider_.$get) { throw $injectorMinErr('pget', "Provider '{0}' must define $get factory method.", name); } return providerCache[name + providerSuffix] = provider_; }
  • 21. provider examples someModule.provider('providerName', function (){ var trackingUrl = '/track'; // A provider method for configuring where the tracked events should been saved this.setTrackingUrl = function(url) { trackingUrl = url; }; // The service factory function this.$get = ['$http', function($http) { var trackedEvents = {}; return { // Call this to track an event event: function(event) { var count = trackedEvents[event] || 0; count += 1; trackedEvents[event] = count; return count; }, // Call this to save the tracked events to the trackingUrl save: function() { $http.post(trackingUrl, trackedEvents); } }; }]; });
  • 22. factory - well known - most widely used - private functions - provider with a $get function - // angular.factory('someFactory', factoryObject)
  • 23. factory source function factory(name, factoryFn, enforce) { return provider(name, { $get: enforce !== false ? enforceReturnValue(name, factoryFn) : factoryFn }); } function enforceReturnValue(name, factory) { return function enforcedReturnValue() { var result = instanceInjector.invoke(factory, this); if (isUndefined(result)) { throw $injectorMinErr('undef', "Provider '{0}' must return a value from $get factory method.", name); } return result; }; }
  • 24. factory examples someModule.factory('ping', ['$http', function($http) { return { ping: function { return $http.send('/ping'); }; }]); someModule.controller('Ctrl', ['ping', function(ping) { ping(); }]); someModule.factory('ping', ['$http', function($http) { return function ping() { return $http.send('/ping'); }; }]); someModule.controller('Ctrl', ['ping', function(ping) { ping(); }]);
  • 25. constant - we all know what constant means - can’t be decorated (not shit, Sherlock) - injectable during config phase - Example: angular.constant('someConstantName', constantValue)
  • 26. constant source function constant(name, value) { assertNotHasOwnProperty(name, 'constant'); providerCache[name] = value; instanceCache[name] = value; }
  • 27. constant – examples someModule.constant('SHARD_HEIGHT', 306); someModule.constant('MY_COLOURS', ['red', 'blue', 'grey']);
  • 28. value - can not be injected in the config phase - represents an angular variable that can be injected and used throughout your providers, directives, controllers example: angular.value('someValue', actualValue)
  • 29. value source function value(name, val) { return factory(name, valueFn(val), false); }
  • 30. service - known but not so widespread - injectable constructor example: angular.service('ServiceName', serviceObj);
  • 31. service source function service(name, constructor) { return factory(name, ['$injector', function($injector) { return $injector.instantiate(constructor); }]); }
  • 32. service examples var ServiceName = function($http) { this.$http = $http; }; ServiceName.$inject = ['$http']; ServiceName.prototype.send = function() { return this.$http.get('/some-http-address'); }; $provide.service('ServiceName', ServiceName); angular.service('ServiceName', function($http){ this.$http = $http; this.send = function() { return this.$http.get('/some-http-address'); }; });
  • 33. decorator - Service instantiation interceptor - Behavior override - Modify / encapsulate other providers - Can decorate every provider, except constant - Less known, barely used - why? - angular-mocks uses it to add flush() to $timeout angular.decorator('someDecorator', decoratorObj);
  • 34. decorator source 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}); }; }
  • 35. decorator example /** * @description * * Here we decorate the ns.$log service to convert warnings to errors */ angular.decorator('$log', ['$delegate', function ($delegate) { delegate.warn = delegate.error; return delegate; }]);
  • 36. Change detection - dirty checking - consists of running equality checks over all of the data that the view depends on