6. Digest cycle
User event
(ng-click)
Sync work in
controllers
Async work in
$http, $timeout
and $interval
scope.$apply
Start from
root scope
Check all
watchers on
scope
more
scopes?
Update UI
value changed
no change
switch to scope and
continue checking
everything’s
done
$digest phase
7. Digest cycle
What about async events?
If you want to update view after receiving async event, you should force a
$apply call.
Don’t do it directly: use $timeout
// Somewhere, an async handler
var handler = function(){
$rootScope.$emit("changeContent");
};
//in your controller
$rootScope.$on("changeContent", function(){
console.log("rootScope event has been fired");
$timeout(function(){ $scope.data = "Data should change"; });
});
11. Registering Services
Module exposes 5 methods to instruct the injector how to evaluate our code
var myApp = angular.module('myApp', [''])
.constant('myConstant', {})
.value('myValue', {})
.service('myService', function(){})
.factory('myService', function(){})
.provider('myService', function(){})
12. Registering Services
Application life-cycle splits in 2 phases
● Configuration phase (app bootstrap)
○ No services
○ Configure and instantiate providers
● Run phase (after config)
○ No Providers interaction
○ Services start being created
13. ● For simple values of any type
● Do not accept DI / being configured
● Can be injected into the config function
myApp.constant('SERVERS',{ DEVELOPMENT: "http://localhost:8080/app", PRODUCTION:"http://myDomain.com/app"});
Constant
myApp.config(function(SERVERS){
console.log(SERVERS.PRODUCTION);
});
myApp.run(function(SERVERS){
console.log(SERVERS.DEVELOPMENT);
})
Definition
CONFIG USAGE RUN USAGE
14. ● Simple objects or primitives
● Do not accept DI / being configured
myApp.value('randomize',function(){ return Math.floor(Math.random()*10000);})
myApp.value('token','a1234567890');
myApp.value('User',{'id': 'someId'})
Value
myApp.run(function(randomize, User){
var num = randomize();
User.id = num;
});
Definition
USAGE
15. ● Constructor function that will be instantiated (internally invokes it with new)
● Cannot being configured
● Arguments represents DEPENDENCIES to be injected
myApp.service('AuthBearer', ['token', function(token) {
this.authValue = "bearer " + token;
}]);
Service
myApp.run(function(AuthBearer){
console.log(AuthBearer.authValue);
})
Definition
USAGE
myApp.value('token','a1234567890');
TOKEN is INJECTED!!!
16. ● Uses DI, No config
● Allows service initialization
myApp.factory('apiToken', ['$window', 'clientId', function apiTokenFactory($window, clientId) {
var encrypt = function(data1, data2) {
// NSA-proof encryption algorithm:
return (data1 + ':' + data2).toUpperCase();
};
var secret = $window.localStorage.getItem('myApp.secret');
var apiToken = encrypt(clientId, secret);
return apiToken;
}]);
Factory
myApp.run(function(apiToken)
{
console.log(apiToken);
})
Definition
USAGE
17. ● Uses DI
● Exposes API for service config before app starts (config phase)
● $get method is a factory function, that creates our service
myApp.provider('logger', function(){
var logToConsole = false;
this.enableConsole = function(flag){
logToConsole = flag;
};
this.$get = function(){
return {
debug: function(msg){ if(logToConsole){ console.log(msg);} }
};
};
})
Provider
Definition
22. Dependency Injection
The Angular injector subsystem is in charge of
creating components,
resolving their dependencies,
and providing them to other components as requested.
24. Dependency Injection
We register our code on the
injector with the provide service
https://docs.angularjs.org/api/auto/service/$provide
The magic behind
27. Dependency Injection
We use the injector to
retrieve object instances
https://docs.angularjs.org/api/auto/service/$injector
The magic behind
28. Dependency Injection
First time we inject a service, the
injector evaluates the code
and stores the result
in an instanceCache object
The magic behind
32. Dependency Injection
3 ways to use DI:
Implicit Annotation
$inject Property Annotation
Inline Array Annotation
How to use it
33. Dependency Injection
Implicit Annotation
How to use it
myApp.controller('MyCtrl', function($scope, logger) {
// ...
});
The Simplest way
If we minify our code, service names as
arguments will be renamed, and app will
break.var MyController = function($scope, logger) {
// ...
}
myApp.controller('MyCtrl', MyController]);
34. Dependency Injection
$inject property Annotation
How to use it
var MyController = function($scope, logger) {
// ...
}
MyController.$inject = ['$scope', 'logger'];
myApp.controller('MyCtrl', MyController);
The Long way
Order of
parameters
must MATCH
35. Dependency Injection
Inline Array Annotation
How to use it
myApp.controller('MyCtrl', ['$scope', 'logger', function($scope, logger)
{
// ...
}]);
The prefered way
var MyController = function($scope, logger) {
// ...
}
myApp.controller('MyCtrl', ['$scope', 'logger',
MyController]);
Order of parameters must MATCH
37. Routes
2 common routing libs
● ngRoute https://docs.angularjs.org/api/ngRoute/service/$route
○ Official
○ Separated in ngRoute module
○ Only one navigation view per application
● ui-router https://angular-ui.github.io/ui-router/
○ Community chosen
○ More powerful
○ More flexible
39. ui-router
What is a ‘state’?
A place in the app, in terms of UI and navigation
Describes how the UI looks like and what does at that place
States are bound to named, nested and parallel views
40. ui-router
Installation
$ bower install angular-ui-router
<script src="angular.js"></script>
<script src="angular-ui-router.js"></script>
angular.module('myApp', ['ui.router']);
Get Package
Include Script
Import Module
42. ui-router
$stateProvider
$state is a service defined with provider method
that gives us $stateProvider to prepare $state at config phase
$state is the ui-router service to handle states
http://angular-ui.github.io/ui-router/site/#/api/ui.router.state.$state
49. use state property abstract:true
abstract states cannot be directly activated
abstract states can have controller
Useful for nested views
ui-router
Abstract states
50. ● abstract states
● nested states
● named states
ui-router
Let’s see a full example with:
51. ui-router
State resolve and callbacks
.state('home', {
resolve: {user: function(){}}, //where function returns a promise
onEnter: function(user){},
onExit: function(user){}
});
56. How filters work
● Every binded expression will have a $watcher.
○ So don’t spare on filters if they improve your life.
● Watchers are checked every digest loop, but only run on changes.
○ Filters take as much time as the function they run.
● Optimization
○ Use one-way binding (::value)
○ If something won’t change, pre-process it, don’t filter it.
○ Avoid DOM filters when possible
○ Beware of dependencies, don’t introduce state.
○ Preferably with strings
http://www.alexkras.com/11-tips-to-improve-angularjs-performance/
https://www.binpress.com/tutorial/speeding-up-angular-js-with-simple-optimizations/135
57. Stateful Filters
Typical case: {{ 'TRANSLATIONID' | translate }}
● The ID never changes but the language does.
● Used on ng-translate.
angular.module('myApp', [])
.filter('translate', ['translationService', function (translationService) {
function translate(input) {
chain_translated += translationService.getChain(input);
return chain_translated;
}
translate.$stateful = true;
return translate;
}]);
http://blog.thoughtram.io/angularjs/2014/11/19/exploring-angular-1.3-stateful-filters.html
59. Directives
Main purpose:
Directives are markers on a DOM element that tell Angular’s HTML “compiler” to
attach a certain behaviour to it (via event listeners).
Structure
● Snake and camelCase naming format
● Restrict roles
● Template vs. TemplateURL
● Controller and controllerAs
● Scope isolation
● Functions
http://weblogs.asp.net/dwahlin/creating-custom-angularjs-directives-part-i-the-fundamentals
60. By intuition you may think that a directive is a component of the template.
That being correct, it is more than that.
Directives can :
● add or modify behaviour of elements
● add real-time dynamism to elements >> two way data binding
● add interactivity with the user
● modify or complement other directives
● add a complete element
● provide code reutilization, for instance: animations, styles ...
● connect elements data and behaviour
Directives
61. Custom Directives: Naming format
Directives are meant to be part of the template so their naming format are
restricted to HTML syntax.
Automatically, camelCase names are understood on the template as Snake
names, see the example below:
app.directive(customDirective, function() {
return { }
});
<custom-directive></custom directive>
<x_custom_directive></x_custom_directive>
<data:custom:directive></data:custom:directive>
62. Custom Directives: Roles
Directives can play different roles in the template:
● Element, attribute, class or comment even. Restrictions should be
applied.
● Element and attribute allow parameters.
● More intuitive to use element, but attribute helps separating CSS.
app.directive(CustomDirective, function() {
return {
restrict: 'EACM',
scope: {},
template: '<div class="sparkline"><h4>Hello world</h4></div>',
controller: function (){},
controllerAs: ‘ctrl1’,
link: function() {},
}
});
WARNING:
Compatibility issues
with C and M.
63. template vs. templateURL
They are equivalent but templateURL is recommended.
● templateURL points to a file template (with path)
○ We can use a function previously defined
○ We can use import mechanisms from requireJS or ES6
● template is the template inline
template: '<div class="sparkline"><h4>Hello world</h4></div>',
templateURL: 'path/to/template.html',
templateURL: tpl,
64. Custom directives: controller
Usually a directive is bound to a controller and this is achieved by defining or
passing the controller to the directive.
controller: function() {return;}
The controller is run after the template is compiled but before the DOM is
completed and the scope linked between directives. So, variables has not been
replaced and data-binding has not been performed.
DON’T MANIPULATE THE DOM HERE
The controller is meant to set the data necessary for the directive and interact
with the rest of the application.
Think of it as the API for the directive.
65. Custom directives: controllerAs
ControllerAs creates a variable in the directive’s scope that will hold the
Controller’s scope:
ControllerAs: ‘ctrl1’,
$scope.ctrl1.something
● Recommended for confusing namespaces
● Avoids overlapping of variables with the same name
● Identifies levels of inheritance
● Using this becomes safer, but you might be using $scope already.
66. @ Text binding passes string values and does one way
binding. Allow interpolation as in the example above.
& One way or once: changes on the directive will not affect
the parent scope. Think of it as a getter.
Can be used to call external functions
= Two way passes objects and changes affect to both
directive and higher scopes (all if not limited).
It is the more magical one but it comes with a cost.
Custom directives: Binding styles
angular.module("myApp",[])
.directive("myDirective", function () {
return {
restrict: "A",
scope: {
text: "@myText",
oneWayBind: "&myOneWayBind",
twoWayBind: "=myTwoWayBind",
name: "="
}
};
}).controller("myController", function ($scope) {
$scope.foo = {name: "zwerty"};
$scope.bar = "qwerty";
$scope.name = "name";
});
<div ng-bind="myController">
<div my-directive
my-text="hello {{ bar }}"
my-two-way-bind="foo"
my-one-way-bind="bar">
</div>
</div>
PAY ATENTION TO {{bar }} in my-text
https://umur.io/angularjs-directives-using-isolated-scope-with-attributes/
67. More on binding styles
● ng-bind is one way.
● ng-model is two way.
● {{ var }} is similar to a one way binding, but it is dirty checked every digest
cycle.
○ Using {{::var}} we limit the checking to the first time (once)is one way.
● So {{ var }} is potentially slower than ng-model because the first is
interpreted every digest cycle.
68. By default a directive inherits the scope of his parent. For example an ng-
controller:
div ng-controller="ParentController">
ParentController: <input type="text" ng-model="foo" />
<custom-directive></custom-directive>
</div>
Inheritance goes all the way to the upper level. And also affects siblings.
Custom directives: Scope inheritance
69. If we initialize the property scope in the directive’s definition we achieve an
isolated scope (at least partially):
scope: {},
scope: true,
scope: {foo: "..."}
Isolation is partial, but controlled, by the data-binding.
Nevertheless, inheritance is still happening as we can see in this example:
http://codepen.io/hectorcanto/pen/JGzdoj
Custom directives: Isolated scope
70. angular.module('directivesModule').directive('isolatedScopeWithController', function () {
return {
restrict: 'EA',
scope: {
datasource: '=',
add: '&',
},
controller: function ($scope) {
...
$scope.addItem = function () {
var name = 'New Item Added by Directive';
$scope.add( )(name);
$scope.items.push({
name: name
});
};
},
template: '<button ng-click="addItem()">Change Data</button><ul>
<li ng-repeat="element in items">{{ element.name }}</li></ul>'
};
});
Custom directives: Isolated scope II
<div isolated-scope-with-controller
datasource="items" add="addCostumer">
</div>
71. There are 3 types of functions, by order of execution:
○ compile, controller and link
● Compile happens once, before the template is compiled.
● The rest of functions is run once for each time the directive is used
■ For example in a ng-repeat of 4 elements, 4 loops
○ Controller initialize the scope.
○ Link happens when the linking is being made, by default after.
○ We can divide link into two, pre-link and post-link
■ Pre-link happens before the element is linked to the scope
■ Post-link happens just after, when the element affected is on the DOM.
● This is the most usual and potentially safest
Custom directives: functions
http://www.undefinednull.com/2014/07/07/practical-guide-to-prelink-postlink-and-controller-methods-of-
angular-directives/
72. Custom directives: link, prelink, postlink
● There are 4 arguments available for these functions (in this order)
○ scope, elements, attributes and controllers
● You can access the DOM, you have the element.
● By default use link directly, which is equivalent to post-link alone.
● Remember, if possible provide values as soon as you can.
○ Don’t wait to post-link, do it in the controller or in compile
● [post-]link is the View part where you have everything in place and you do
the last adjustments and decisions regarding the DOM.
73. Custom directives: link, prelink, postlink
var app = angular.module('app', []);
app.directive('dad', function () {
return {
restrict: 'EA',
template: '<div class="dad">{{greeting}}{{name}}'+
'<son></son>'+
'</div>',
link: {
pre: function(scope,elem,attr){
scope.name = 'Paul';
scope.greeting = 'Hey, I am ';
}
}
};
})
app.directive('son', function () {
return {
restrict: 'EA',
template: '<div class="son">{{sonSays}}</div>',
link: function(scope,elem,attr){
scope.sonSays = 'Hey, I am David, and my dad
is '+ scope.name;
}
};
});
<div ng-app="app">
<dad></dad>
</div>
Hey, I am Paul
Hey, I am David, and my dad is Paul
http://jsfiddle.net/shidhincr/Bpxn2/1/?utm_source=website&utm_medium=embed&utm_campaign=Bpxn2
74. Custom directives: post-link,
● It is safe to manipulate the DOM in post-link as the element is already in
the DOM.
● It is possible to access the scope
● All child directives are linked so it’s safe to access them
○ their scope and the elements they affect.
● It is safe to attach events handlers to elements.
75. Custom directives: pre-link,
● Use of pre-link is scarce,
○ A child needs data from its parent
● Safe to attach an event to the DOM element
○ Not safe to access DOM elements from child directives
● The scope is not linked yet.
76. Custom directives: compile
● In this phase AngularJS manipulates the DOM of the HTML template
● Each directive has a chance to do some processing for all and each DOM
nodes it appears in.
● The scope is not attached yet.
● The template is still bare, without binding nor substitutions.
77. THANKS FOR YOUR ATTENTION
Leave your questions on the comments section