SlideShare a Scribd company logo
1 of 23
Download to read offline
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

What's hot

What's hot (20)

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

Viewers also liked

Reactive.architecture.with.Angular
Reactive.architecture.with.AngularReactive.architecture.with.Angular
Reactive.architecture.with.Angular
Evan Schultz
 
Comercio electronico
Comercio electronicoComercio electronico
Comercio electronico
mariangelarod
 
Derechos del niño
Derechos del niñoDerechos del niño
Derechos del niño
Tony Hotter
 
Nâng cao năng lực của các trường cao đẳng nghề vùng đồng bằng sông h...
Nâng cao năng lực của các trường cao đẳng nghề vùng đồng bằng sông h...Nâng cao năng lực của các trường cao đẳng nghề vùng đồng bằng sông h...
Nâng cao năng lực của các trường cao đẳng nghề vùng đồng bằng sông h...
https://www.facebook.com/garmentspace
 

Viewers also liked (16)

Reactive.architecture.with.Angular
Reactive.architecture.with.AngularReactive.architecture.with.Angular
Reactive.architecture.with.Angular
 
Ionic
IonicIonic
Ionic
 
Ionic: Hybrid Mobile Apps... made simple
Ionic: Hybrid Mobile Apps... made simpleIonic: Hybrid Mobile Apps... made simple
Ionic: Hybrid Mobile Apps... made simple
 
Comercio electronico
Comercio electronicoComercio electronico
Comercio electronico
 
Derechos del niño
Derechos del niñoDerechos del niño
Derechos del niño
 
Ritusmoi_Kaushik_Resume
Ritusmoi_Kaushik_ResumeRitusmoi_Kaushik_Resume
Ritusmoi_Kaushik_Resume
 
Buenas tortas
Buenas tortasBuenas tortas
Buenas tortas
 
Apresentação Renova - Institucional
Apresentação Renova - InstitucionalApresentação Renova - Institucional
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...
Nâng cao năng lực của các trường cao đẳng nghề vùng đồng bằng sông h...Nâng cao năng lực của các trường cao đẳng nghề vùng đồng bằng sông h...
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
Building cross platform app with Xamarin FormsBuilding cross platform app with Xamarin Forms
Building cross platform app with Xamarin Forms
 
Ti g4 final
Ti g4 finalTi g4 final
Ti g4 final
 
Angular 2 Component Communication - Talk by Rob McDiarmid
Angular 2 Component Communication - Talk by Rob McDiarmidAngular 2 Component Communication - Talk by Rob McDiarmid
Angular 2 Component Communication - Talk by Rob McDiarmid
 
Dislexia, disgrafía y dificultades habituales 6
Dislexia, disgrafía y dificultades habituales   6Dislexia, disgrafía y dificultades habituales   6
Dislexia, disgrafía y dificultades habituales 6
 
Hybrid Apps with Ionic Framework
Hybrid Apps with Ionic FrameworkHybrid Apps with Ionic Framework
Hybrid Apps with Ionic Framework
 
Misses
MissesMisses
Misses
 

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

Angular Presentation
Angular PresentationAngular Presentation
Angular Presentation
Adam Moore
 

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

introduction to Angularjs basics
introduction to Angularjs basicsintroduction to Angularjs basics
introduction to Angularjs basics
 
Angular Interview Questions-PDF.pdf
Angular Interview Questions-PDF.pdfAngular Interview Questions-PDF.pdf
Angular Interview Questions-PDF.pdf
 
Angular Presentation
Angular PresentationAngular Presentation
Angular Presentation
 
17612235.ppt
17612235.ppt17612235.ppt
17612235.ppt
 
AngularJS in practice
AngularJS in practiceAngularJS in practice
AngularJS in practice
 
AngularJs-training
AngularJs-trainingAngularJs-training
AngularJs-training
 
Directives
DirectivesDirectives
Directives
 
React Hooks Best Practices in 2022.pptx
React Hooks Best Practices in 2022.pptxReact Hooks Best Practices in 2022.pptx
React Hooks Best Practices in 2022.pptx
 
Intoduction to Angularjs
Intoduction to AngularjsIntoduction to Angularjs
Intoduction to Angularjs
 
Angular2 and You
Angular2 and YouAngular2 and You
Angular2 and You
 
Angular Project Report
 Angular Project Report Angular Project Report
Angular Project Report
 
Angular js-crash-course
Angular js-crash-courseAngular js-crash-course
Angular js-crash-course
 
Angular.pptx
Angular.pptxAngular.pptx
Angular.pptx
 
ANGULAR JS LAB MANUAL(final) vtu2021 sch
ANGULAR JS LAB MANUAL(final) vtu2021 schANGULAR JS LAB MANUAL(final) vtu2021 sch
ANGULAR JS LAB MANUAL(final) vtu2021 sch
 
AngularJs Crash Course
AngularJs Crash CourseAngularJs Crash Course
AngularJs Crash Course
 
AngularJS Beginner Day One
AngularJS Beginner Day OneAngularJS Beginner Day One
AngularJS Beginner Day One
 
AngularJS Basics
AngularJS BasicsAngularJS Basics
AngularJS Basics
 
Angular Directives
Angular DirectivesAngular Directives
Angular Directives
 
Understanding angular js
Understanding angular jsUnderstanding angular js
Understanding angular js
 
mean stack
mean stackmean stack
mean stack
 

Recently uploaded

Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
dharasingh5698
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
ssuser89054b
 

Recently uploaded (20)

chapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineeringchapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineering
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdf
 
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
 
Intze Overhead Water Tank Design by Working Stress - IS Method.pdf
Intze Overhead Water Tank  Design by Working Stress - IS Method.pdfIntze Overhead Water Tank  Design by Working Stress - IS Method.pdf
Intze Overhead Water Tank Design by Working Stress - IS Method.pdf
 
Vivazz, Mieres Social Housing Design Spain
Vivazz, Mieres Social Housing Design SpainVivazz, Mieres Social Housing Design Spain
Vivazz, Mieres Social Housing Design Spain
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPT
 
Online banking management system project.pdf
Online banking management system project.pdfOnline banking management system project.pdf
Online banking management system project.pdf
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - V
 
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
 
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . ppt
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
 
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELLPVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
 
Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghly
 
NFPA 5000 2024 standard .
NFPA 5000 2024 standard                                  .NFPA 5000 2024 standard                                  .
NFPA 5000 2024 standard .
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
 
Call for Papers - International Journal of Intelligent Systems and Applicatio...
Call for Papers - International Journal of Intelligent Systems and Applicatio...Call for Papers - International Journal of Intelligent Systems and Applicatio...
Call for Papers - International Journal of Intelligent Systems and Applicatio...
 

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) { ... }