SlideShare a Scribd company logo
Get rid of controllers in
AngularJS 1.5.x
Start using component directives
Fakiolas Marios - fakiolasmarios@gmail.com / @fakiolinho
Frontend Developer at mist.io, creator of angularjs-recipes.com
What are
component
directives in
AngularJS 1.5 ?
As of AngularJS 1.5.x release a new type of
directives was introduced. These are component
directives.
A component directive is a component with directives
flavor.
This is a huge step which brings us closer to
components logic even in AngularJS 1.5.x
We can now build an AngularJS 1.5.x application by
replacing controllers with components.
So we can prepare even better our old applications
for their upgrade to Angular 2 and its components
ways.
Let’s create
a simple
component
directive
// Create it
angular
.module('myApp')
.component('userGreeting', {
bindings: {
user: '='
},
controller: function() {
var self = this;
self.welcome = 'Welcome ' + self.user.name + '!';
},
template: '<h1>{{$ctrl.welcome}}</h1>'
});
// Use it
<user-greeting user="{name: 'John Doe'}"></user-greeting>
<user-greeting user="{name: 'Jane Doe'}"></user-greeting>
Analyze a
simple
component
directive
name
This is the name of the component and the only
required option. We should pick wisely a camel-case
name to register our component and then call it into
action using this. Be careful because it always maps
to a dash-case component:
angular
.module('myApp')
.component('userGreeting', {
...
});
<user-greeting user="{name: 'John Doe'}"></user-greeting>
Analyze a
simple
component
directive
bindings
This an optional parameter and it is the way to
define DOM attribute binding to component
properties. Component properties are always bound
to the component controller.
angular
.module('myApp')
.component('userGreeting', {
bindings: {
user: '='
},
...
});
<user-greeting user="{name: 'John Doe'}"></user-greeting>
Analyze a
simple
component
directive
controller
This is an optional parameter and by default an
empty function is registered. Here we can use all
attributes passed with bindings and run some logic.
angular
.module('myApp')
.component('userGreeting', {
bindings: {
user: '='
},
controller: function() {
var self = this;
self.welcome = 'Welcome ' + self.user.name + '!';
}
...
});
Analyze a
simple
component
directive
template
This is an optional parameter which returns an
empty string by default. We can register with it a
html template as the content of our component.
Check out offered $ctrl as a controller’s alias.
angular
.module('myApp')
.component('userGreeting', {
bindings: {
user: '='
},
controller: function() {
var self = this;
self.welcome = 'Welcome ' + self.user.name + '!';
},
template: '<h1>{{$ctrl.welcome}}</h1>'
});
Analyze a
simple
component
directive
templateUrl
We could use this to call into action an external
html file as our component’s template.
angular
.module('myApp')
.component('userGreeting', {
bindings: {
user: '='
},
controller: function() {
var self = this;
self.welcome = 'Welcome ' + self.user.name + '!';
},
templateUrl: 'greeting.html'
});
Are you
still ok?
Let’s create
a simple
Blog
application
with
component
directives
https://github.com/Athens-AngularJS-Meetup/blog
Routing with
component
directives
// Routing using components instead of controllers
angular
.module('myApp')
.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/', {
resolve: {
posts: function(Post) {
return Post.all();
}
},
template: '<posts posts="$resolve.posts"></posts>'
})
...
Declaring
posts
component
// Posts list component
angular
.module('myApp')
.component('posts', {
templateUrl: 'app/templates/posts.html',
bindings: {
posts: '='
},
controller: function() {
var self = this;
self.posts = self.posts.slice(0, 5);
}
});
Declaring
posts list
and post-
item
templates
// Posts list template
<section id="posts">
<post-item post="post" ng-repeat="post in $ctrl.posts"></post-item>
</section>
// Post list item template
<div class="post-item card">
<img ng-src="{{$ctrl.img}}" alt="{{$ctrl.post.title}}" />
<div class="card-body">
<h4>{{$ctrl.post.title}}</h4>
<hr>
<p>{{$ctrl.post.body}}</p>
<a ng-href="#/posts/{{$ctrl.post.id}}" class="btn">Read
More</a>
</div>
</div>
Declaring
post-item
component
// Post item component
angular
.module('myApp')
.component('postItem', {
templateUrl: 'app/templates/post-item.html',
bindings: {
post: '<'
},
controller: function() {
var self = this;
self.img = 'http://lorempixel.com/600/300/city/';
}
});
Declaring
Post factory
// Posts factory
angular
.module('myApp')
.factory('Post', ['$http', function($http) {
var service = {
all: all,
get: get
};
return service;
function all() {
return $http
.get('http://jsonplaceholder.typicode.com/posts')
.then(function(data) {
return data.data;
});
}
...
Create even
more
components
like social-
icons
// Declare the component
angular
.module('myApp')
.component('socialIcons', {
templateUrl: 'app/templates/social-icons.html'
});
// Declare its template
<ul class="social-icons">
<li>
<a href="#"><i class="fa fa-twitter"></i></a>
</li>
...
</ul>
// Use the component
<social-icons></social-icons>
Components
data
bindings
overview
Components
bindings
type does
matter a lot
bindings: {
// Two way data-bindings (avoid usage)
posts: '=',
// One way data-bindings
// Preferable for Objects (highly proposed)
post: '<',
// Preferable for simple Strings
name: '@',
// Outputs data-bindings
onEdit: '&'
}
Components
bindings
type does
matter a lot
Ideally, the whole application should be a tree of
components that implement clearly defined inputs
and outputs, and minimize two-way data binding.
That way, it's easier to predict when data changes
and what the state of a component is.
Inputs should be using < and @ bindings. The <
symbol denotes one-way bindings (available since
1.5). The difference to = is that the bound properties
in the component scope are not watched, which
means if you assign a new value to the property in
the component scope, it will not update the parent
scope.
Components
bindings
type does
matter a lot
Note however, that both parent and component
scope reference the same object, so if you are
changing object properties or array elements in the
component, the parent will still reflect that change.
The general rule should therefore be to never
change an object or array property in the component
scope.
Components
cooperation
Of course components have outputs too. These are
also declared in bindings and we use them to inform
a parent component regarding an edit / delete /
update action we want to execute.
Data flow always from parents to children and
children never edit their inputs but emit the right
callback events backwards to their parents
requesting an action.
Outputs are realized with & bindings, which function
as callbacks to component events.
That way, the parent component can decide what to
do with the event (e.g. delete an item or update the
properties)
Components
cooperation
example
// Child's input / output bindings
bindings: {
task: '<',
onDelete: '&'
}
// Child's template
<p>{{$ctrl.post.title}}</p>
<button ng-click="$ctrl.onDelete({post: $ctrl.post})">Delete</button>
//Parent's template
<section id="posts">
<post-item post="post" on-delete="$ctrl.deletePost(post)" ng-repeat="post
in $ctrl.posts"></post-item>
</section>
// Parent's controller
ctrl.deletePost(post) {
...
}
Get rid of controllers in angular 1.5.x start using component directives

More Related Content

PDF
Web components are the future of the web - Take advantage of new web technolo...
PDF
Data Flow Patterns in Angular 2 - Sebastian Müller
PPTX
PPTX
What are the components in React?
PDF
AngularJS - Services
PPTX
Dive into Angular, part 4: Angular 2.0
PPTX
AngularJS Fundamentals + WebAPI
PPTX
React render props
Web components are the future of the web - Take advantage of new web technolo...
Data Flow Patterns in Angular 2 - Sebastian Müller
What are the components in React?
AngularJS - Services
Dive into Angular, part 4: Angular 2.0
AngularJS Fundamentals + WebAPI
React render props

What's hot (20)

PPTX
AngularJS2 / TypeScript / CLI
PPTX
Dive into Angular, part 1: Introduction
PPTX
Dive into Angular, part 3: Performance
PDF
Angular from Scratch
PPTX
AngularJs presentation
PDF
Redux and context api with react native app introduction, use cases, implemen...
PDF
Angular2 workshop
PDF
The productive developer guide to Angular 2
PDF
Angular 2 - An Introduction
PDF
Angular 4 for Java Developers
PDF
Extending Kubernetes with Operators
PPTX
React js programming concept
PDF
JOSA TechTalks - Better Web Apps with React and Redux
PPTX
Angular2 + rxjs
PDF
Angular Dependency Injection
PDF
React native app with type script tutorial
PDF
Introduction to Angular 2
PDF
Top 7 Angular Best Practices to Organize Your Angular App
PDF
Getting Started with React-Nathan Smith
PPTX
Dive into Angular, part 5: Experience
AngularJS2 / TypeScript / CLI
Dive into Angular, part 1: Introduction
Dive into Angular, part 3: Performance
Angular from Scratch
AngularJs presentation
Redux and context api with react native app introduction, use cases, implemen...
Angular2 workshop
The productive developer guide to Angular 2
Angular 2 - An Introduction
Angular 4 for Java Developers
Extending Kubernetes with Operators
React js programming concept
JOSA TechTalks - Better Web Apps with React and Redux
Angular2 + rxjs
Angular Dependency Injection
React native app with type script tutorial
Introduction to Angular 2
Top 7 Angular Best Practices to Organize Your Angular App
Getting Started with React-Nathan Smith
Dive into Angular, part 5: Experience
Ad

Viewers also liked (16)

PDF
Reactive.architecture.with.Angular
PDF
PDF
Ionic: Hybrid Mobile Apps... made simple
PPTX
Comercio electronico
DOCX
Derechos del niño
PDF
Ritusmoi_Kaushik_Resume
PPTX
Buenas tortas
PDF
Apresentação Renova - Institucional
PPTX
музей охраны природы
PDF
Nâng cao năng lực của các trường cao đẳng nghề vùng đồng bằng sông h...
PDF
Building cross platform app with Xamarin Forms
PDF
Ti g4 final
PDF
Angular 2 Component Communication - Talk by Rob McDiarmid
PDF
Dislexia, disgrafía y dificultades habituales 6
PDF
Hybrid Apps with Ionic Framework
PPS
Reactive.architecture.with.Angular
Ionic: Hybrid Mobile Apps... made simple
Comercio electronico
Derechos del niño
Ritusmoi_Kaushik_Resume
Buenas tortas
Apresentação Renova - Institucional
музей охраны природы
Nâng cao năng lực của các trường cao đẳng nghề vùng đồng bằng sông h...
Building cross platform app with Xamarin Forms
Ti g4 final
Angular 2 Component Communication - Talk by Rob McDiarmid
Dislexia, disgrafía y dificultades habituales 6
Hybrid Apps with Ionic Framework
Ad

Similar to Get rid of controllers in angular 1.5.x start using component directives (20)

PPTX
AngularJs Workshop SDP December 28th 2014
PPTX
angularJs Workshop
PDF
Angular Rebooted: Components Everywhere
PDF
Angular Rebooted: Components Everywhere - Carlo Bonamico, Sonia Pini - Codemo...
PPTX
Angular js 1.3 presentation for fed nov 2014
PDF
Angularjs
PDF
Angular.js Primer in Aalto University
PDF
Angular custom directives
PDF
AngularJS: an introduction
PPTX
Intro to AngularJs
PPTX
Angular Workshop_Sarajevo2
PDF
Building Custom AngularJS Directives - A Step-by-Step Guide - Dan Wahlin | Fa...
PPT
Angular js
PPT
Angular js
PDF
Angular Directives from Scratch
PPTX
Introduction to AngularJs
PPTX
Introduction to Angular JS
PPTX
Angular workshop - Full Development Guide
PPTX
AngularJS
PPTX
Angular Presentation
AngularJs Workshop SDP December 28th 2014
angularJs Workshop
Angular Rebooted: Components Everywhere
Angular Rebooted: Components Everywhere - Carlo Bonamico, Sonia Pini - Codemo...
Angular js 1.3 presentation for fed nov 2014
Angularjs
Angular.js Primer in Aalto University
Angular custom directives
AngularJS: an introduction
Intro to AngularJs
Angular Workshop_Sarajevo2
Building Custom AngularJS Directives - A Step-by-Step Guide - Dan Wahlin | Fa...
Angular js
Angular js
Angular Directives from Scratch
Introduction to AngularJs
Introduction to Angular JS
Angular workshop - Full Development Guide
AngularJS
Angular Presentation

Recently uploaded (20)

PPTX
web development for engineering and engineering
PPTX
CYBER-CRIMES AND SECURITY A guide to understanding
PPTX
UNIT-1 - COAL BASED THERMAL POWER PLANTS
PPTX
Lecture Notes Electrical Wiring System Components
PPTX
Construction Project Organization Group 2.pptx
PPTX
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
PPTX
additive manufacturing of ss316l using mig welding
PPT
Mechanical Engineering MATERIALS Selection
PPTX
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
PPTX
Sustainable Sites - Green Building Construction
PDF
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
PDF
Structs to JSON How Go Powers REST APIs.pdf
PDF
Operating System & Kernel Study Guide-1 - converted.pdf
PPT
Project quality management in manufacturing
PPTX
bas. eng. economics group 4 presentation 1.pptx
PPTX
Geodesy 1.pptx...............................................
PDF
Well-logging-methods_new................
PDF
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
PPTX
Strings in CPP - Strings in C++ are sequences of characters used to store and...
PDF
Arduino robotics embedded978-1-4302-3184-4.pdf
web development for engineering and engineering
CYBER-CRIMES AND SECURITY A guide to understanding
UNIT-1 - COAL BASED THERMAL POWER PLANTS
Lecture Notes Electrical Wiring System Components
Construction Project Organization Group 2.pptx
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
additive manufacturing of ss316l using mig welding
Mechanical Engineering MATERIALS Selection
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
Sustainable Sites - Green Building Construction
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
Structs to JSON How Go Powers REST APIs.pdf
Operating System & Kernel Study Guide-1 - converted.pdf
Project quality management in manufacturing
bas. eng. economics group 4 presentation 1.pptx
Geodesy 1.pptx...............................................
Well-logging-methods_new................
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
Strings in CPP - Strings in C++ are sequences of characters used to store and...
Arduino robotics embedded978-1-4302-3184-4.pdf

Get rid of controllers in angular 1.5.x start using component directives

  • 1. Get rid of controllers in AngularJS 1.5.x Start using component directives Fakiolas Marios - fakiolasmarios@gmail.com / @fakiolinho Frontend Developer at mist.io, creator of angularjs-recipes.com
  • 2. What are component directives in AngularJS 1.5 ? As of AngularJS 1.5.x release a new type of directives was introduced. These are component directives. A component directive is a component with directives flavor. This is a huge step which brings us closer to components logic even in AngularJS 1.5.x We can now build an AngularJS 1.5.x application by replacing controllers with components. So we can prepare even better our old applications for their upgrade to Angular 2 and its components ways.
  • 3. Let’s create a simple component directive // Create it angular .module('myApp') .component('userGreeting', { bindings: { user: '=' }, controller: function() { var self = this; self.welcome = 'Welcome ' + self.user.name + '!'; }, template: '<h1>{{$ctrl.welcome}}</h1>' }); // Use it <user-greeting user="{name: 'John Doe'}"></user-greeting> <user-greeting user="{name: 'Jane Doe'}"></user-greeting>
  • 4. Analyze a simple component directive name This is the name of the component and the only required option. We should pick wisely a camel-case name to register our component and then call it into action using this. Be careful because it always maps to a dash-case component: angular .module('myApp') .component('userGreeting', { ... }); <user-greeting user="{name: 'John Doe'}"></user-greeting>
  • 5. Analyze a simple component directive bindings This an optional parameter and it is the way to define DOM attribute binding to component properties. Component properties are always bound to the component controller. angular .module('myApp') .component('userGreeting', { bindings: { user: '=' }, ... }); <user-greeting user="{name: 'John Doe'}"></user-greeting>
  • 6. Analyze a simple component directive controller This is an optional parameter and by default an empty function is registered. Here we can use all attributes passed with bindings and run some logic. angular .module('myApp') .component('userGreeting', { bindings: { user: '=' }, controller: function() { var self = this; self.welcome = 'Welcome ' + self.user.name + '!'; } ... });
  • 7. Analyze a simple component directive template This is an optional parameter which returns an empty string by default. We can register with it a html template as the content of our component. Check out offered $ctrl as a controller’s alias. angular .module('myApp') .component('userGreeting', { bindings: { user: '=' }, controller: function() { var self = this; self.welcome = 'Welcome ' + self.user.name + '!'; }, template: '<h1>{{$ctrl.welcome}}</h1>' });
  • 8. Analyze a simple component directive templateUrl We could use this to call into action an external html file as our component’s template. angular .module('myApp') .component('userGreeting', { bindings: { user: '=' }, controller: function() { var self = this; self.welcome = 'Welcome ' + self.user.name + '!'; }, templateUrl: 'greeting.html' });
  • 11. Routing with component directives // Routing using components instead of controllers angular .module('myApp') .config(['$routeProvider', function($routeProvider) { $routeProvider .when('/', { resolve: { posts: function(Post) { return Post.all(); } }, template: '<posts posts="$resolve.posts"></posts>' }) ...
  • 12. Declaring posts component // Posts list component angular .module('myApp') .component('posts', { templateUrl: 'app/templates/posts.html', bindings: { posts: '=' }, controller: function() { var self = this; self.posts = self.posts.slice(0, 5); } });
  • 13. Declaring posts list and post- item templates // Posts list template <section id="posts"> <post-item post="post" ng-repeat="post in $ctrl.posts"></post-item> </section> // Post list item template <div class="post-item card"> <img ng-src="{{$ctrl.img}}" alt="{{$ctrl.post.title}}" /> <div class="card-body"> <h4>{{$ctrl.post.title}}</h4> <hr> <p>{{$ctrl.post.body}}</p> <a ng-href="#/posts/{{$ctrl.post.id}}" class="btn">Read More</a> </div> </div>
  • 14. Declaring post-item component // Post item component angular .module('myApp') .component('postItem', { templateUrl: 'app/templates/post-item.html', bindings: { post: '<' }, controller: function() { var self = this; self.img = 'http://lorempixel.com/600/300/city/'; } });
  • 15. Declaring Post factory // Posts factory angular .module('myApp') .factory('Post', ['$http', function($http) { var service = { all: all, get: get }; return service; function all() { return $http .get('http://jsonplaceholder.typicode.com/posts') .then(function(data) { return data.data; }); } ...
  • 16. Create even more components like social- icons // Declare the component angular .module('myApp') .component('socialIcons', { templateUrl: 'app/templates/social-icons.html' }); // Declare its template <ul class="social-icons"> <li> <a href="#"><i class="fa fa-twitter"></i></a> </li> ... </ul> // Use the component <social-icons></social-icons>
  • 18. Components bindings type does matter a lot bindings: { // Two way data-bindings (avoid usage) posts: '=', // One way data-bindings // Preferable for Objects (highly proposed) post: '<', // Preferable for simple Strings name: '@', // Outputs data-bindings onEdit: '&' }
  • 19. Components bindings type does matter a lot Ideally, the whole application should be a tree of components that implement clearly defined inputs and outputs, and minimize two-way data binding. That way, it's easier to predict when data changes and what the state of a component is. Inputs should be using < and @ bindings. The < symbol denotes one-way bindings (available since 1.5). The difference to = is that the bound properties in the component scope are not watched, which means if you assign a new value to the property in the component scope, it will not update the parent scope.
  • 20. Components bindings type does matter a lot Note however, that both parent and component scope reference the same object, so if you are changing object properties or array elements in the component, the parent will still reflect that change. The general rule should therefore be to never change an object or array property in the component scope.
  • 21. Components cooperation Of course components have outputs too. These are also declared in bindings and we use them to inform a parent component regarding an edit / delete / update action we want to execute. Data flow always from parents to children and children never edit their inputs but emit the right callback events backwards to their parents requesting an action. Outputs are realized with & bindings, which function as callbacks to component events. That way, the parent component can decide what to do with the event (e.g. delete an item or update the properties)
  • 22. Components cooperation example // Child's input / output bindings bindings: { task: '<', onDelete: '&' } // Child's template <p>{{$ctrl.post.title}}</p> <button ng-click="$ctrl.onDelete({post: $ctrl.post})">Delete</button> //Parent's template <section id="posts"> <post-item post="post" on-delete="$ctrl.deletePost(post)" ng-repeat="post in $ctrl.posts"></post-item> </section> // Parent's controller ctrl.deletePost(post) { ... }