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

Dive into Angular, part 1: Introduction
Dive into Angular, part 1: IntroductionDive into Angular, part 1: Introduction
Dive into Angular, part 1: IntroductionOleksii Prohonnyi
 
Dive into Angular, part 3: Performance
Dive into Angular, part 3: PerformanceDive into Angular, part 3: Performance
Dive into Angular, part 3: PerformanceOleksii Prohonnyi
 
AngularJs presentation
AngularJs presentation AngularJs presentation
AngularJs presentation Phan Tuan
 
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...Katy Slemon
 
Angular2 workshop
Angular2 workshopAngular2 workshop
Angular2 workshopNir Kaufman
 
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 2Maurice De Beijer [MVP]
 
Angular 4 for Java Developers
Angular 4 for Java DevelopersAngular 4 for Java Developers
Angular 4 for Java DevelopersYakov Fain
 
Extending Kubernetes with Operators
Extending Kubernetes with OperatorsExtending Kubernetes with Operators
Extending Kubernetes with Operatorspeychevi
 
React js programming concept
React js programming conceptReact js programming concept
React js programming conceptTariqul islam
 
Angular Dependency Injection
Angular Dependency InjectionAngular Dependency Injection
Angular Dependency InjectionNir Kaufman
 
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 tutorialKaty Slemon
 
Introduction to Angular 2
Introduction to Angular 2Introduction to Angular 2
Introduction to Angular 2Naveen Pete
 
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 AppKaty Slemon
 
Getting Started with React-Nathan Smith
Getting Started with React-Nathan SmithGetting Started with React-Nathan Smith
Getting Started with React-Nathan SmithTandemSeven
 
Dive into Angular, part 5: Experience
Dive into Angular, part 5: ExperienceDive into Angular, part 5: Experience
Dive into Angular, part 5: ExperienceOleksii Prohonnyi
 

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.AngularEvan Schultz
 
Ionic: Hybrid Mobile Apps... made simple
Ionic: Hybrid Mobile Apps... made simpleIonic: Hybrid Mobile Apps... made simple
Ionic: Hybrid Mobile Apps... made simpleCommit University
 
Comercio electronico
Comercio electronicoComercio electronico
Comercio electronicomariangelarod
 
Derechos del niño
Derechos del niñoDerechos del niño
Derechos del niñoTony Hotter
 
Apresentação Renova - Institucional
Apresentação Renova - InstitucionalApresentação Renova - Institucional
Apresentação Renova - Institucionalmgboni
 
музей охраны природы
музей охраны природымузей охраны природы
музей охраны природыschool68vrn
 
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
 
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 FormsAurelian Maga
 
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 McDiarmidAmrita Chopra
 
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 6gesfomediaeducacion
 
Hybrid Apps with Ionic Framework
Hybrid Apps with Ionic FrameworkHybrid Apps with Ionic Framework
Hybrid Apps with Ionic FrameworkBramus Van Damme
 

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

introduction to Angularjs basics
introduction to Angularjs basicsintroduction to Angularjs basics
introduction to Angularjs basicsRavindra K
 
Angular Interview Questions-PDF.pdf
Angular Interview Questions-PDF.pdfAngular Interview Questions-PDF.pdf
Angular Interview Questions-PDF.pdfJohnLeo57
 
Angular Presentation
Angular PresentationAngular Presentation
Angular PresentationAdam Moore
 
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.pptxBOSC Tech Labs
 
Intoduction to Angularjs
Intoduction to AngularjsIntoduction to Angularjs
Intoduction to AngularjsGaurav Agrawal
 
Angular Project Report
 Angular Project Report Angular Project Report
Angular Project ReportKodexhub
 
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 schkannikadg
 
AngularJS Beginner Day One
AngularJS Beginner Day OneAngularJS Beginner Day One
AngularJS Beginner Day OneTroy Miles
 
AngularJS Basics
AngularJS BasicsAngularJS Basics
AngularJS BasicsRavi Mone
 
Understanding angular js
Understanding angular jsUnderstanding angular js
Understanding angular jsAayush Shrestha
 

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

UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performancesivaprakash250
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Dr.Costas Sachpazis
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...roncy bisnoi
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdfankushspencer015
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...Soham Mondal
 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Christo Ananth
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escortsranjana rawat
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxupamatechverse
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130Suhani Kapoor
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINESIVASHANKAR N
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlysanyuktamishra911
 
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...Call Girls in Nagpur High Profile
 
result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college projectTonystark477637
 
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...ranjana rawat
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxpurnimasatapathy1234
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxpranjaldaimarysona
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxupamatechverse
 

Recently uploaded (20)

Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performance
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptx
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghly
 
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...
 
result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college project
 
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptx
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptx
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptx
 

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