SlideShare a Scribd company logo
Creating
ANGULAR JS
Custom Directives
The coolest feature you’ve ever used.
Let’s find out what it is!
Declarative &
Model-Driven
Behavior
Imperativeness equals your problem.
Declarative approach means colliding with
somebody else’s problem. Also extending HTML.
core concept #1
Modularity &
Reusability
across contexts
Directives know their own element and local scope.
We can pass additional data into directives as
attributes, right on element.
Write once, run anywhere!
core concept #2
Keep it Local
Sticks to a self-contained, modular scope, which
understands its context: inside the directive,
‘element’ is like ‘this’.
Uses messages, models to affect things elsewhere.
Easier to maintain, easier to read, easier to scale.
core concept #3
We know Angular Built-In Directives
 ng-app
 ng-bind
 ng-model
 ng-class
 ng-controller
 ng-show / ng-hide
 ng-if
 ng-switch
Generally speaking, a directive is a function that’s
attached to an element. But not JUST. It is a whole
execution environment.
Basic Angular JS directives you
are usually using
How are custom directives
different from built-in?
They are different only in naming conventions. Do
not use ‘ng-’ in your custom directives.
Naming Custom Directives
Angular uses a convention borrowed from other JS
projects: names in HTML are hyphenated (snake
case) while identifiers in the JS are camel-cased.
Expect Angular to do this conversion automatically
because of normalization process.
Directive name in HTML and
Normalization
.directive(‘customDir’) function () {
// Some code goes here
})
<custom-dir></custom-dir>
<span custom:dir></span>
<span custom_dir></span>
…
Let’s
CREATE
Custom Directive
Directive is the heart of Angular JS Framework
Building Custom Directive
Custom Directive Creating
Process
angular
.module(‘moduleName’, [‘dep1’, ‘dep2’])
.directive(‘directiveName’) factoryFunction () {
// Some code goes here
})  .directive() is a method we call on an
angular.module(), either at creation time or via
reference, passing a name and a factory function
 The factory will return either a function or an
object containing a function and other settings
When we talk about generic ‘factories’, we don’t mean $factory, which is an Angular
implementation service. The factory pattern is all about Functional Programming: using
basic JavaScript functions to build and return naiive objects or other functions.
What do we do with the factory function?
There are two basic options
 Returning only the link function
 Link versus Compile
 Pre-Link versus Post-Link
How to choose? Link or configuration object? What is Pre-Link and Post-Link functions?
All these relate to $compile service of Angular JS and recommended for high-skilled
developers.
 Return a configuration object
 Return a ‘linking function
But now IGNORE for today:
Using Config Object
Today we need to remember that directive returns
an object. We may use the list of properties.
Remember, link property is optional.
Returning object with directives’
configurations
angular.module(‘moduleName’, [])
.directive(‘customDir’) function () {
return {
link: function (scope, element, attrs) {
element.bind(‘mouseenter’, function () {
});
},
restrict: ‘ECMA’,
template: ‘<div>Hello, World</div>’
};
});
Link Function Arguments
Directives that want to modify the DOM typically use the
link option to register DOM listeners as well as update the
DOM.
 scope - is an Angular scope object.
 element - is the jqLite-wrapped element that this
directive matches (declared on ‘this’).
 attrs - object containing the HTML attributes defined
on the element, including the directive invocating itself.
 controller - is the directive's required controller
instance(s) or it's own controller (optional).
 transcludeFn is a transclude linking function pre-bound
to the correct transclusion scope (optional).
Creating a Directive that
Manipulates the DOM
angular.module(‘moduleName’, [])
.directive(‘customDir’) function () {
return {
link: function (scope, element, attrs) {
element.bind(‘mouseenter’, function () {
});
},
restrict: ‘ECMA’,
template: ‘<div>Hello, World</div>’
};
});
Link Function Arguments
$scope is assignable, but should be reserved for
angular functions to pass into a controller, other
context. It is a shorthand, by which we’re calling the
$scopeProvider, which is Dependency-Injecting the
scope for us.
scope is just our own, customizable reference for
directive’s local scope.
$scope VERSUS scopeangular.module(‘moduleName’, [])
.directive(‘customDir’) function () {
return {
link: function (scope, element, attrs) {
element.bind(‘mouseenter’, function () {
});
},
restrict: ‘ECMA’,
template: ‘<div>Hello, World</div>’
};
});
Using jqLite
Angular will defer to jQuery, if present, but provides
its own subset of jQuery for basic DOM tasks. You
can not just use ‘$( )’, nor find using selectors,
unfortunately.
But all built-in ‘element’ refs are already pre-
wrapped in jqLite object. Try to chain methods as
you normally would.
You can use Angular jqLite for
basic DOM tasks
 addClass()
 after()
 append()
 attr()
 bind()
 children()
 clone()
 contents()
 css()
 data()
 eq()
 find()
 hasClass()
 html()
 nest()
 on()
 off()
 parent()
 prepend()
 prop()
 ready()
 remove()
 removeAttr()
 removeClass()
 removeData()
 replaceWith()
 text()
 toggleClass()
 triggerHandler()
 unbind()
 val()
 wrap()
Using jqLite
$(‘selector’).bind(‘mouseenter’, function () {});
The same as..
angular.module(‘moduleName’, [])
.directive(‘customDir’) function () {
return {
link: function (scope, element, attrs) {
element.bind(‘mouseenter’, function () {
do some stuff..
});
},
restrict: ‘ECMA’,
template: ‘<div>Hello, World</div>’
};
});
Let’s review another ‘modern’
directives’ options…
Templating in Directive
template – property where we can store our
template as a string.
templateUrl – this property allows us to load
template from a file, using path.
Use the template you need
angular.module(‘moduleName’, [])
.directive(‘customDir’) function () {
return {
link: function (scope, element, attrs) {
element.bind(‘mouseenter’, function () {
});
},
restrict: ‘ECMA’,
template: ‘<div>Hello, World</div>’,
// or
templateUrl: ‘path/dir/template.html’
};
});
Restrict Property
Remember that directives are re-usable. We can restrict
the usage of a directive to (a) specific context(s).
Defaults to ‘A’. Stack as a single string ‘EACM’.
 ‘E’lement,
 ‘A’ttribute,
 ‘C’lass,
 co’M’ment.
Memorize like ECMAScript
<custom></custom>
<span custom=“somevalue”></span>
<span class=“custom_dir”></span>
<!– directive: custom somevalue -->
angular.module(‘moduleName’, [])
.directive(‘customDir’) function () {
return {
restrict: ‘ECMA’,
};
});
Replace Property [DEPRECATED]
By default, a directive element will wrap the
contents of a template. The ‘element’ object will be
the outer directive element. To instead replace the
directive element (and object) with the contents of
the template, use replace: true
This is especially critical when declaring as an
element.
Wrap without showing directive
element
angular.module(‘moduleName’, [])
.directive(‘customDir’) function () {
return {
replace: true,
template: ‘<header>Some info</header>’
};
});
<body>
<custom-dir>
<header>
Some info
</header>
</custom-dir>
</body>
Directive Isolate Scope
We have the option, in directives, of using either: the
local $scope (from our own controller, possibly) and a
new, per-instance, ‘isolate scope’.
Isolate scopes still have a parent $scope, but they’re
‘eccapsulated’ or, in other words, detached from the
inheritance chain. This is especially useful with repeats,
so variables can be fully local to the instance
Using isolate scope in a custom
directive
.directive(‘customDir’) function () {
return {
scope: true, // creates child scope
template: ‘<div>Hello, World</div>’
};
});
.directive(‘customDir’) function () {
return {
scope: {
dataSet: ‘@’,
}, // creates isolated scope
template: ‘<div>Hello, World</div>’
};
});
Isolate Scope Data-Binding
Angular provides us with ways to bind the value of properties in
isolate scope to attributes on the element, using special operators.
By default, an operator alone will be assumed to refer to a same-
named attr.
‘@’ - binds the local scope property to primitive value of the DOM
attribute. Result is always a string because attributes are strings.
‘=‘ - binds the local scope property to a parent scope property
having same name as the value of the DOM attribute.
‘&’ - binds local scope property to the output of an expression
defined in the DOM attribute. It’s like a function wrapper.
Ways to bind values of properties
.directive(‘customDir’) function () {
return {
scope: {
job: ‘@job’, // or only ‘@’
},
template: ‘<div>Hello, World</div>’
};
});
<custom job=“dev”></custom>
scope: {
job: ‘@’,
}
// the same as
scope.job = attrs.job;
You also
NEED TO KNOW
Something MORE
You should re-view some information about custom
directives by yourself
Try to find…
 Transclude
 Controller
 controllerAs
 Require
…more about such properties
You will need this information in the future to create
more complex custom directives, using them as the
LEGO blocks.
References
…Learn more
Angular Directives from Scratch
Creating Custom Directives
Comprehensive Directive API
Thank You!
This presentation was created specially for
if058.Web-UI Group.
Yaroslav Prodanchuk
prepared by:

More Related Content

What's hot

Custom AngularJS Directives
Custom AngularJS DirectivesCustom AngularJS Directives
Custom AngularJS Directives
yprodev
 
AngularJS for designers and developers
AngularJS for designers and developersAngularJS for designers and developers
AngularJS for designers and developersKai Koenig
 
AngularJS Directives
AngularJS DirectivesAngularJS Directives
AngularJS Directives
Eyal Vardi
 
AngularJS Basic Training
AngularJS Basic TrainingAngularJS Basic Training
AngularJS Basic Training
Cornel Stefanache
 
Angular JS
Angular JSAngular JS
Angular JS
John Temoty Roca
 
Angular js
Angular jsAngular js
Angular js
Manav Prasad
 
AngularJS Basics with Example
AngularJS Basics with ExampleAngularJS Basics with Example
AngularJS Basics with Example
Sergey Bolshchikov
 
AngularJS Architecture
AngularJS ArchitectureAngularJS Architecture
AngularJS Architecture
Eyal Vardi
 
The AngularJS way
The AngularJS wayThe AngularJS way
The AngularJS way
Boyan Mihaylov
 
Getting Started with Angular JS
Getting Started with Angular JSGetting Started with Angular JS
Getting Started with Angular JS
Akshay Mathur
 
Understanding angular js
Understanding angular jsUnderstanding angular js
Understanding angular js
Aayush Shrestha
 
Angular js architecture (v1.4.8)
Angular js architecture (v1.4.8)Angular js architecture (v1.4.8)
Angular js architecture (v1.4.8)
Gabi Costel Lapusneanu
 
Practical AngularJS
Practical AngularJSPractical AngularJS
Practical AngularJS
Wei Ru
 
Angular js 1.0-fundamentals
Angular js 1.0-fundamentalsAngular js 1.0-fundamentals
Angular js 1.0-fundamentals
Venkatesh Narayanan
 
Dynamic Application Development by NodeJS ,AngularJS with OrientDB
Dynamic Application Development by NodeJS ,AngularJS with OrientDBDynamic Application Development by NodeJS ,AngularJS with OrientDB
Dynamic Application Development by NodeJS ,AngularJS with OrientDB
Apaichon Punopas
 
Angular Js Basics
Angular Js BasicsAngular Js Basics
Angular Js Basics
أحمد عبد الوهاب
 
Angular JS - Introduction
Angular JS - IntroductionAngular JS - Introduction
Angular JS - Introduction
Sagar Acharya
 
AngularJS Internal
AngularJS InternalAngularJS Internal
AngularJS Internal
Eyal Vardi
 
Advanced Tips & Tricks for using Angular JS
Advanced Tips & Tricks for using Angular JSAdvanced Tips & Tricks for using Angular JS
Advanced Tips & Tricks for using Angular JS
Simon Guest
 

What's hot (20)

Custom AngularJS Directives
Custom AngularJS DirectivesCustom AngularJS Directives
Custom AngularJS Directives
 
AngularJS for designers and developers
AngularJS for designers and developersAngularJS for designers and developers
AngularJS for designers and developers
 
AngularJS Directives
AngularJS DirectivesAngularJS Directives
AngularJS Directives
 
AngularJS Basic Training
AngularJS Basic TrainingAngularJS Basic Training
AngularJS Basic Training
 
Angular JS
Angular JSAngular JS
Angular JS
 
Angular js
Angular jsAngular js
Angular js
 
AngularJS Basics with Example
AngularJS Basics with ExampleAngularJS Basics with Example
AngularJS Basics with Example
 
AngularJS Architecture
AngularJS ArchitectureAngularJS Architecture
AngularJS Architecture
 
The AngularJS way
The AngularJS wayThe AngularJS way
The AngularJS way
 
Getting Started with Angular JS
Getting Started with Angular JSGetting Started with Angular JS
Getting Started with Angular JS
 
Understanding angular js
Understanding angular jsUnderstanding angular js
Understanding angular js
 
Angular js architecture (v1.4.8)
Angular js architecture (v1.4.8)Angular js architecture (v1.4.8)
Angular js architecture (v1.4.8)
 
Practical AngularJS
Practical AngularJSPractical AngularJS
Practical AngularJS
 
Angular js 1.0-fundamentals
Angular js 1.0-fundamentalsAngular js 1.0-fundamentals
Angular js 1.0-fundamentals
 
Dynamic Application Development by NodeJS ,AngularJS with OrientDB
Dynamic Application Development by NodeJS ,AngularJS with OrientDBDynamic Application Development by NodeJS ,AngularJS with OrientDB
Dynamic Application Development by NodeJS ,AngularJS with OrientDB
 
Angular js
Angular jsAngular js
Angular js
 
Angular Js Basics
Angular Js BasicsAngular Js Basics
Angular Js Basics
 
Angular JS - Introduction
Angular JS - IntroductionAngular JS - Introduction
Angular JS - Introduction
 
AngularJS Internal
AngularJS InternalAngularJS Internal
AngularJS Internal
 
Advanced Tips & Tricks for using Angular JS
Advanced Tips & Tricks for using Angular JSAdvanced Tips & Tricks for using Angular JS
Advanced Tips & Tricks for using Angular JS
 

Viewers also liked

Coffee@DBG - Exploring Angular JS
Coffee@DBG - Exploring Angular JSCoffee@DBG - Exploring Angular JS
Coffee@DBG - Exploring Angular JS
Deepu S Nath
 
Building an End-to-End AngularJS Application
Building an End-to-End AngularJS ApplicationBuilding an End-to-End AngularJS Application
Building an End-to-End AngularJS Application
Dan Wahlin
 
Getting Started Building Windows 8 HTML/JavaScript Metro Apps
Getting Started Building Windows 8 HTML/JavaScript Metro AppsGetting Started Building Windows 8 HTML/JavaScript Metro Apps
Getting Started Building Windows 8 HTML/JavaScript Metro Apps
Dan Wahlin
 
Angular promises and http
Angular promises and httpAngular promises and http
Angular promises and http
Alexe Bogdan
 
AngularJS in 60ish Minutes
AngularJS in 60ish MinutesAngularJS in 60ish Minutes
AngularJS in 60ish Minutes
Dan Wahlin
 
Using jQuery Templates
Using jQuery TemplatesUsing jQuery Templates
Using jQuery Templates
Dan Wahlin
 
JavaScript Patterns to Cleanup your Code
JavaScript Patterns to Cleanup your CodeJavaScript Patterns to Cleanup your Code
JavaScript Patterns to Cleanup your Code
Dan Wahlin
 
Angular Promises and Advanced Routing
Angular Promises and Advanced RoutingAngular Promises and Advanced Routing
Angular Promises and Advanced Routing
Alexe Bogdan
 
Building the an End-to-End ASP.NET MVC 4, Entity Framework, HTML5, jQuery app...
Building the an End-to-End ASP.NET MVC 4, Entity Framework, HTML5, jQuery app...Building the an End-to-End ASP.NET MVC 4, Entity Framework, HTML5, jQuery app...
Building the an End-to-End ASP.NET MVC 4, Entity Framework, HTML5, jQuery app...
Dan Wahlin
 
Development Trends - What's New in the World of Web Development
Development Trends - What's New in the World of Web DevelopmentDevelopment Trends - What's New in the World of Web Development
Development Trends - What's New in the World of Web Development
Dan Wahlin
 
Integrating Security Roles into Microsoft Silverlight Applications
Integrating Security Roles into Microsoft Silverlight ApplicationsIntegrating Security Roles into Microsoft Silverlight Applications
Integrating Security Roles into Microsoft Silverlight ApplicationsDan Wahlin
 
Planificación y organización de dominio
Planificación y organización de dominioPlanificación y organización de dominio
Planificación y organización de dominio
lilidani103
 
Spa Architecture with Durandal and Friends
Spa Architecture with Durandal and FriendsSpa Architecture with Durandal and Friends
Spa Architecture with Durandal and Friends
Johnny Tordgeman
 
AngularJS Best Practices
AngularJS Best PracticesAngularJS Best Practices
AngularJS Best Practices
Betclic Everest Group Tech Team
 
AngularJS Testing
AngularJS TestingAngularJS Testing
AngularJS Testing
Eyal Vardi
 
Nodejs
NodejsNodejs
Nodejs
Eyal Vardi
 
Getting Started with ASP.NET MVC 3 and Razor
Getting Started with ASP.NET MVC 3 and RazorGetting Started with ASP.NET MVC 3 and Razor
Getting Started with ASP.NET MVC 3 and RazorDan Wahlin
 
AngularJS Compile Process
AngularJS Compile ProcessAngularJS Compile Process
AngularJS Compile Process
Eyal Vardi
 
Node.js Spplication Scaling
Node.js Spplication ScalingNode.js Spplication Scaling
Node.js Spplication Scaling
Eyal Vardi
 
Rachel's grandmother's recipes
Rachel's grandmother's recipesRachel's grandmother's recipes
Rachel's grandmother's recipes
Eyal Vardi
 

Viewers also liked (20)

Coffee@DBG - Exploring Angular JS
Coffee@DBG - Exploring Angular JSCoffee@DBG - Exploring Angular JS
Coffee@DBG - Exploring Angular JS
 
Building an End-to-End AngularJS Application
Building an End-to-End AngularJS ApplicationBuilding an End-to-End AngularJS Application
Building an End-to-End AngularJS Application
 
Getting Started Building Windows 8 HTML/JavaScript Metro Apps
Getting Started Building Windows 8 HTML/JavaScript Metro AppsGetting Started Building Windows 8 HTML/JavaScript Metro Apps
Getting Started Building Windows 8 HTML/JavaScript Metro Apps
 
Angular promises and http
Angular promises and httpAngular promises and http
Angular promises and http
 
AngularJS in 60ish Minutes
AngularJS in 60ish MinutesAngularJS in 60ish Minutes
AngularJS in 60ish Minutes
 
Using jQuery Templates
Using jQuery TemplatesUsing jQuery Templates
Using jQuery Templates
 
JavaScript Patterns to Cleanup your Code
JavaScript Patterns to Cleanup your CodeJavaScript Patterns to Cleanup your Code
JavaScript Patterns to Cleanup your Code
 
Angular Promises and Advanced Routing
Angular Promises and Advanced RoutingAngular Promises and Advanced Routing
Angular Promises and Advanced Routing
 
Building the an End-to-End ASP.NET MVC 4, Entity Framework, HTML5, jQuery app...
Building the an End-to-End ASP.NET MVC 4, Entity Framework, HTML5, jQuery app...Building the an End-to-End ASP.NET MVC 4, Entity Framework, HTML5, jQuery app...
Building the an End-to-End ASP.NET MVC 4, Entity Framework, HTML5, jQuery app...
 
Development Trends - What's New in the World of Web Development
Development Trends - What's New in the World of Web DevelopmentDevelopment Trends - What's New in the World of Web Development
Development Trends - What's New in the World of Web Development
 
Integrating Security Roles into Microsoft Silverlight Applications
Integrating Security Roles into Microsoft Silverlight ApplicationsIntegrating Security Roles into Microsoft Silverlight Applications
Integrating Security Roles into Microsoft Silverlight Applications
 
Planificación y organización de dominio
Planificación y organización de dominioPlanificación y organización de dominio
Planificación y organización de dominio
 
Spa Architecture with Durandal and Friends
Spa Architecture with Durandal and FriendsSpa Architecture with Durandal and Friends
Spa Architecture with Durandal and Friends
 
AngularJS Best Practices
AngularJS Best PracticesAngularJS Best Practices
AngularJS Best Practices
 
AngularJS Testing
AngularJS TestingAngularJS Testing
AngularJS Testing
 
Nodejs
NodejsNodejs
Nodejs
 
Getting Started with ASP.NET MVC 3 and Razor
Getting Started with ASP.NET MVC 3 and RazorGetting Started with ASP.NET MVC 3 and Razor
Getting Started with ASP.NET MVC 3 and Razor
 
AngularJS Compile Process
AngularJS Compile ProcessAngularJS Compile Process
AngularJS Compile Process
 
Node.js Spplication Scaling
Node.js Spplication ScalingNode.js Spplication Scaling
Node.js Spplication Scaling
 
Rachel's grandmother's recipes
Rachel's grandmother's recipesRachel's grandmother's recipes
Rachel's grandmother's recipes
 

Similar to AngularJS Custom Directives

Directives
DirectivesDirectives
Directives
Brajesh Yadav
 
AngularJs-training
AngularJs-trainingAngularJs-training
AngularJs-training
Pratchaya Suputsopon
 
Angular - Chapter 5 - Directives
 Angular - Chapter 5 - Directives Angular - Chapter 5 - Directives
Angular - Chapter 5 - Directives
WebStackAcademy
 
AngularJS.part1
AngularJS.part1AngularJS.part1
AngularJS.part1
Andrey Kolodnitsky
 
AngularJs Crash Course
AngularJs Crash CourseAngularJs Crash Course
AngularJs Crash Course
Keith Bloomfield
 
Angular In Depth
Angular In DepthAngular In Depth
Angular In Depth
Mindfire Solutions
 
Angular.js Primer in Aalto University
Angular.js Primer in Aalto UniversityAngular.js Primer in Aalto University
Angular.js Primer in Aalto University
SC5.io
 
Modular javascript
Modular javascriptModular javascript
Modular javascriptZain Shaikh
 
Angular js-crash-course
Angular js-crash-courseAngular js-crash-course
Angular js-crash-course
Keith Bloomfield
 
AngularJs Workshop SDP December 28th 2014
AngularJs Workshop SDP December 28th 2014AngularJs Workshop SDP December 28th 2014
AngularJs Workshop SDP December 28th 2014
Ran Wahle
 
angularJs Workshop
angularJs WorkshopangularJs Workshop
angularJs Workshop
Ran Wahle
 
AngularJS 101 - Everything you need to know to get started
AngularJS 101 - Everything you need to know to get startedAngularJS 101 - Everything you need to know to get started
AngularJS 101 - Everything you need to know to get started
Stéphane Bégaudeau
 
Angular js
Angular jsAngular js
Angular js
Baldeep Sohal
 
Angular workshop - Full Development Guide
Angular workshop - Full Development GuideAngular workshop - Full Development Guide
Angular workshop - Full Development Guide
Nitin Giri
 
Opinionated AngularJS
Opinionated AngularJSOpinionated AngularJS
Opinionated AngularJS
prabhutech
 
AngularJS
AngularJSAngularJS
AngularJS
LearningTech
 
AngularJS in practice
AngularJS in practiceAngularJS in practice
AngularJS in practice
Eugene Fidelin
 
How AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design PatternsHow AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design Patterns
Ran Mizrahi
 
KnockOutjs from Scratch
KnockOutjs from ScratchKnockOutjs from Scratch
KnockOutjs from ScratchUdaya Kumar
 

Similar to AngularJS Custom Directives (20)

Directives
DirectivesDirectives
Directives
 
AngularJs-training
AngularJs-trainingAngularJs-training
AngularJs-training
 
Angular - Chapter 5 - Directives
 Angular - Chapter 5 - Directives Angular - Chapter 5 - Directives
Angular - Chapter 5 - Directives
 
AngularJS.part1
AngularJS.part1AngularJS.part1
AngularJS.part1
 
AngularJs Crash Course
AngularJs Crash CourseAngularJs Crash Course
AngularJs Crash Course
 
Angular In Depth
Angular In DepthAngular In Depth
Angular In Depth
 
Angular.js Primer in Aalto University
Angular.js Primer in Aalto UniversityAngular.js Primer in Aalto University
Angular.js Primer in Aalto University
 
Modular javascript
Modular javascriptModular javascript
Modular javascript
 
Angular js-crash-course
Angular js-crash-courseAngular js-crash-course
Angular js-crash-course
 
AngularJs Workshop SDP December 28th 2014
AngularJs Workshop SDP December 28th 2014AngularJs Workshop SDP December 28th 2014
AngularJs Workshop SDP December 28th 2014
 
angularJs Workshop
angularJs WorkshopangularJs Workshop
angularJs Workshop
 
Angular - Beginner
Angular - BeginnerAngular - Beginner
Angular - Beginner
 
AngularJS 101 - Everything you need to know to get started
AngularJS 101 - Everything you need to know to get startedAngularJS 101 - Everything you need to know to get started
AngularJS 101 - Everything you need to know to get started
 
Angular js
Angular jsAngular js
Angular js
 
Angular workshop - Full Development Guide
Angular workshop - Full Development GuideAngular workshop - Full Development Guide
Angular workshop - Full Development Guide
 
Opinionated AngularJS
Opinionated AngularJSOpinionated AngularJS
Opinionated AngularJS
 
AngularJS
AngularJSAngularJS
AngularJS
 
AngularJS in practice
AngularJS in practiceAngularJS in practice
AngularJS in practice
 
How AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design PatternsHow AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design Patterns
 
KnockOutjs from Scratch
KnockOutjs from ScratchKnockOutjs from Scratch
KnockOutjs from Scratch
 

Recently uploaded

1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样
1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样
1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样
3ipehhoa
 
Output determination SAP S4 HANA SAP SD CC
Output determination SAP S4 HANA SAP SD CCOutput determination SAP S4 HANA SAP SD CC
Output determination SAP S4 HANA SAP SD CC
ShahulHameed54211
 
原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样
原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样
原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样
3ipehhoa
 
The+Prospects+of+E-Commerce+in+China.pptx
The+Prospects+of+E-Commerce+in+China.pptxThe+Prospects+of+E-Commerce+in+China.pptx
The+Prospects+of+E-Commerce+in+China.pptx
laozhuseo02
 
guildmasters guide to ravnica Dungeons & Dragons 5...
guildmasters guide to ravnica Dungeons & Dragons 5...guildmasters guide to ravnica Dungeons & Dragons 5...
guildmasters guide to ravnica Dungeons & Dragons 5...
Rogerio Filho
 
This 7-second Brain Wave Ritual Attracts Money To You.!
This 7-second Brain Wave Ritual Attracts Money To You.!This 7-second Brain Wave Ritual Attracts Money To You.!
This 7-second Brain Wave Ritual Attracts Money To You.!
nirahealhty
 
Latest trends in computer networking.pptx
Latest trends in computer networking.pptxLatest trends in computer networking.pptx
Latest trends in computer networking.pptx
JungkooksNonexistent
 
ER(Entity Relationship) Diagram for online shopping - TAE
ER(Entity Relationship) Diagram for online shopping - TAEER(Entity Relationship) Diagram for online shopping - TAE
ER(Entity Relationship) Diagram for online shopping - TAE
Himani415946
 
History+of+E-commerce+Development+in+China-www.cfye-commerce.shop
History+of+E-commerce+Development+in+China-www.cfye-commerce.shopHistory+of+E-commerce+Development+in+China-www.cfye-commerce.shop
History+of+E-commerce+Development+in+China-www.cfye-commerce.shop
laozhuseo02
 
BASIC C++ lecture NOTE C++ lecture 3.pptx
BASIC C++ lecture NOTE C++ lecture 3.pptxBASIC C++ lecture NOTE C++ lecture 3.pptx
BASIC C++ lecture NOTE C++ lecture 3.pptx
natyesu
 
test test test test testtest test testtest test testtest test testtest test ...
test test  test test testtest test testtest test testtest test testtest test ...test test  test test testtest test testtest test testtest test testtest test ...
test test test test testtest test testtest test testtest test testtest test ...
Arif0071
 
Living-in-IT-era-Module-7-Imaging-and-Design-for-Social-Impact.pptx
Living-in-IT-era-Module-7-Imaging-and-Design-for-Social-Impact.pptxLiving-in-IT-era-Module-7-Imaging-and-Design-for-Social-Impact.pptx
Living-in-IT-era-Module-7-Imaging-and-Design-for-Social-Impact.pptx
TristanJasperRamos
 
How to Use Contact Form 7 Like a Pro.pptx
How to Use Contact Form 7 Like a Pro.pptxHow to Use Contact Form 7 Like a Pro.pptx
How to Use Contact Form 7 Like a Pro.pptx
Gal Baras
 
急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
3ipehhoa
 
Multi-cluster Kubernetes Networking- Patterns, Projects and Guidelines
Multi-cluster Kubernetes Networking- Patterns, Projects and GuidelinesMulti-cluster Kubernetes Networking- Patterns, Projects and Guidelines
Multi-cluster Kubernetes Networking- Patterns, Projects and Guidelines
Sanjeev Rampal
 
1.Wireless Communication System_Wireless communication is a broad term that i...
1.Wireless Communication System_Wireless communication is a broad term that i...1.Wireless Communication System_Wireless communication is a broad term that i...
1.Wireless Communication System_Wireless communication is a broad term that i...
JeyaPerumal1
 

Recently uploaded (16)

1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样
1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样
1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样
 
Output determination SAP S4 HANA SAP SD CC
Output determination SAP S4 HANA SAP SD CCOutput determination SAP S4 HANA SAP SD CC
Output determination SAP S4 HANA SAP SD CC
 
原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样
原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样
原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样
 
The+Prospects+of+E-Commerce+in+China.pptx
The+Prospects+of+E-Commerce+in+China.pptxThe+Prospects+of+E-Commerce+in+China.pptx
The+Prospects+of+E-Commerce+in+China.pptx
 
guildmasters guide to ravnica Dungeons & Dragons 5...
guildmasters guide to ravnica Dungeons & Dragons 5...guildmasters guide to ravnica Dungeons & Dragons 5...
guildmasters guide to ravnica Dungeons & Dragons 5...
 
This 7-second Brain Wave Ritual Attracts Money To You.!
This 7-second Brain Wave Ritual Attracts Money To You.!This 7-second Brain Wave Ritual Attracts Money To You.!
This 7-second Brain Wave Ritual Attracts Money To You.!
 
Latest trends in computer networking.pptx
Latest trends in computer networking.pptxLatest trends in computer networking.pptx
Latest trends in computer networking.pptx
 
ER(Entity Relationship) Diagram for online shopping - TAE
ER(Entity Relationship) Diagram for online shopping - TAEER(Entity Relationship) Diagram for online shopping - TAE
ER(Entity Relationship) Diagram for online shopping - TAE
 
History+of+E-commerce+Development+in+China-www.cfye-commerce.shop
History+of+E-commerce+Development+in+China-www.cfye-commerce.shopHistory+of+E-commerce+Development+in+China-www.cfye-commerce.shop
History+of+E-commerce+Development+in+China-www.cfye-commerce.shop
 
BASIC C++ lecture NOTE C++ lecture 3.pptx
BASIC C++ lecture NOTE C++ lecture 3.pptxBASIC C++ lecture NOTE C++ lecture 3.pptx
BASIC C++ lecture NOTE C++ lecture 3.pptx
 
test test test test testtest test testtest test testtest test testtest test ...
test test  test test testtest test testtest test testtest test testtest test ...test test  test test testtest test testtest test testtest test testtest test ...
test test test test testtest test testtest test testtest test testtest test ...
 
Living-in-IT-era-Module-7-Imaging-and-Design-for-Social-Impact.pptx
Living-in-IT-era-Module-7-Imaging-and-Design-for-Social-Impact.pptxLiving-in-IT-era-Module-7-Imaging-and-Design-for-Social-Impact.pptx
Living-in-IT-era-Module-7-Imaging-and-Design-for-Social-Impact.pptx
 
How to Use Contact Form 7 Like a Pro.pptx
How to Use Contact Form 7 Like a Pro.pptxHow to Use Contact Form 7 Like a Pro.pptx
How to Use Contact Form 7 Like a Pro.pptx
 
急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
 
Multi-cluster Kubernetes Networking- Patterns, Projects and Guidelines
Multi-cluster Kubernetes Networking- Patterns, Projects and GuidelinesMulti-cluster Kubernetes Networking- Patterns, Projects and Guidelines
Multi-cluster Kubernetes Networking- Patterns, Projects and Guidelines
 
1.Wireless Communication System_Wireless communication is a broad term that i...
1.Wireless Communication System_Wireless communication is a broad term that i...1.Wireless Communication System_Wireless communication is a broad term that i...
1.Wireless Communication System_Wireless communication is a broad term that i...
 

AngularJS Custom Directives

  • 1. Creating ANGULAR JS Custom Directives The coolest feature you’ve ever used. Let’s find out what it is!
  • 2. Declarative & Model-Driven Behavior Imperativeness equals your problem. Declarative approach means colliding with somebody else’s problem. Also extending HTML. core concept #1
  • 3. Modularity & Reusability across contexts Directives know their own element and local scope. We can pass additional data into directives as attributes, right on element. Write once, run anywhere! core concept #2
  • 4. Keep it Local Sticks to a self-contained, modular scope, which understands its context: inside the directive, ‘element’ is like ‘this’. Uses messages, models to affect things elsewhere. Easier to maintain, easier to read, easier to scale. core concept #3
  • 5. We know Angular Built-In Directives  ng-app  ng-bind  ng-model  ng-class  ng-controller  ng-show / ng-hide  ng-if  ng-switch Generally speaking, a directive is a function that’s attached to an element. But not JUST. It is a whole execution environment. Basic Angular JS directives you are usually using How are custom directives different from built-in? They are different only in naming conventions. Do not use ‘ng-’ in your custom directives.
  • 6. Naming Custom Directives Angular uses a convention borrowed from other JS projects: names in HTML are hyphenated (snake case) while identifiers in the JS are camel-cased. Expect Angular to do this conversion automatically because of normalization process. Directive name in HTML and Normalization .directive(‘customDir’) function () { // Some code goes here }) <custom-dir></custom-dir> <span custom:dir></span> <span custom_dir></span> …
  • 7. Let’s CREATE Custom Directive Directive is the heart of Angular JS Framework
  • 8. Building Custom Directive Custom Directive Creating Process angular .module(‘moduleName’, [‘dep1’, ‘dep2’]) .directive(‘directiveName’) factoryFunction () { // Some code goes here })  .directive() is a method we call on an angular.module(), either at creation time or via reference, passing a name and a factory function  The factory will return either a function or an object containing a function and other settings When we talk about generic ‘factories’, we don’t mean $factory, which is an Angular implementation service. The factory pattern is all about Functional Programming: using basic JavaScript functions to build and return naiive objects or other functions.
  • 9. What do we do with the factory function? There are two basic options  Returning only the link function  Link versus Compile  Pre-Link versus Post-Link How to choose? Link or configuration object? What is Pre-Link and Post-Link functions? All these relate to $compile service of Angular JS and recommended for high-skilled developers.  Return a configuration object  Return a ‘linking function But now IGNORE for today:
  • 10. Using Config Object Today we need to remember that directive returns an object. We may use the list of properties. Remember, link property is optional. Returning object with directives’ configurations angular.module(‘moduleName’, []) .directive(‘customDir’) function () { return { link: function (scope, element, attrs) { element.bind(‘mouseenter’, function () { }); }, restrict: ‘ECMA’, template: ‘<div>Hello, World</div>’ }; });
  • 11. Link Function Arguments Directives that want to modify the DOM typically use the link option to register DOM listeners as well as update the DOM.  scope - is an Angular scope object.  element - is the jqLite-wrapped element that this directive matches (declared on ‘this’).  attrs - object containing the HTML attributes defined on the element, including the directive invocating itself.  controller - is the directive's required controller instance(s) or it's own controller (optional).  transcludeFn is a transclude linking function pre-bound to the correct transclusion scope (optional). Creating a Directive that Manipulates the DOM angular.module(‘moduleName’, []) .directive(‘customDir’) function () { return { link: function (scope, element, attrs) { element.bind(‘mouseenter’, function () { }); }, restrict: ‘ECMA’, template: ‘<div>Hello, World</div>’ }; });
  • 12. Link Function Arguments $scope is assignable, but should be reserved for angular functions to pass into a controller, other context. It is a shorthand, by which we’re calling the $scopeProvider, which is Dependency-Injecting the scope for us. scope is just our own, customizable reference for directive’s local scope. $scope VERSUS scopeangular.module(‘moduleName’, []) .directive(‘customDir’) function () { return { link: function (scope, element, attrs) { element.bind(‘mouseenter’, function () { }); }, restrict: ‘ECMA’, template: ‘<div>Hello, World</div>’ }; });
  • 13. Using jqLite Angular will defer to jQuery, if present, but provides its own subset of jQuery for basic DOM tasks. You can not just use ‘$( )’, nor find using selectors, unfortunately. But all built-in ‘element’ refs are already pre- wrapped in jqLite object. Try to chain methods as you normally would. You can use Angular jqLite for basic DOM tasks  addClass()  after()  append()  attr()  bind()  children()  clone()  contents()  css()  data()  eq()  find()  hasClass()  html()  nest()  on()  off()  parent()  prepend()  prop()  ready()  remove()  removeAttr()  removeClass()  removeData()  replaceWith()  text()  toggleClass()  triggerHandler()  unbind()  val()  wrap()
  • 14. Using jqLite $(‘selector’).bind(‘mouseenter’, function () {}); The same as.. angular.module(‘moduleName’, []) .directive(‘customDir’) function () { return { link: function (scope, element, attrs) { element.bind(‘mouseenter’, function () { do some stuff.. }); }, restrict: ‘ECMA’, template: ‘<div>Hello, World</div>’ }; }); Let’s review another ‘modern’ directives’ options…
  • 15. Templating in Directive template – property where we can store our template as a string. templateUrl – this property allows us to load template from a file, using path. Use the template you need angular.module(‘moduleName’, []) .directive(‘customDir’) function () { return { link: function (scope, element, attrs) { element.bind(‘mouseenter’, function () { }); }, restrict: ‘ECMA’, template: ‘<div>Hello, World</div>’, // or templateUrl: ‘path/dir/template.html’ }; });
  • 16. Restrict Property Remember that directives are re-usable. We can restrict the usage of a directive to (a) specific context(s). Defaults to ‘A’. Stack as a single string ‘EACM’.  ‘E’lement,  ‘A’ttribute,  ‘C’lass,  co’M’ment. Memorize like ECMAScript <custom></custom> <span custom=“somevalue”></span> <span class=“custom_dir”></span> <!– directive: custom somevalue --> angular.module(‘moduleName’, []) .directive(‘customDir’) function () { return { restrict: ‘ECMA’, }; });
  • 17. Replace Property [DEPRECATED] By default, a directive element will wrap the contents of a template. The ‘element’ object will be the outer directive element. To instead replace the directive element (and object) with the contents of the template, use replace: true This is especially critical when declaring as an element. Wrap without showing directive element angular.module(‘moduleName’, []) .directive(‘customDir’) function () { return { replace: true, template: ‘<header>Some info</header>’ }; }); <body> <custom-dir> <header> Some info </header> </custom-dir> </body>
  • 18. Directive Isolate Scope We have the option, in directives, of using either: the local $scope (from our own controller, possibly) and a new, per-instance, ‘isolate scope’. Isolate scopes still have a parent $scope, but they’re ‘eccapsulated’ or, in other words, detached from the inheritance chain. This is especially useful with repeats, so variables can be fully local to the instance Using isolate scope in a custom directive .directive(‘customDir’) function () { return { scope: true, // creates child scope template: ‘<div>Hello, World</div>’ }; }); .directive(‘customDir’) function () { return { scope: { dataSet: ‘@’, }, // creates isolated scope template: ‘<div>Hello, World</div>’ }; });
  • 19. Isolate Scope Data-Binding Angular provides us with ways to bind the value of properties in isolate scope to attributes on the element, using special operators. By default, an operator alone will be assumed to refer to a same- named attr. ‘@’ - binds the local scope property to primitive value of the DOM attribute. Result is always a string because attributes are strings. ‘=‘ - binds the local scope property to a parent scope property having same name as the value of the DOM attribute. ‘&’ - binds local scope property to the output of an expression defined in the DOM attribute. It’s like a function wrapper. Ways to bind values of properties .directive(‘customDir’) function () { return { scope: { job: ‘@job’, // or only ‘@’ }, template: ‘<div>Hello, World</div>’ }; }); <custom job=“dev”></custom> scope: { job: ‘@’, } // the same as scope.job = attrs.job;
  • 20. You also NEED TO KNOW Something MORE You should re-view some information about custom directives by yourself
  • 21. Try to find…  Transclude  Controller  controllerAs  Require …more about such properties You will need this information in the future to create more complex custom directives, using them as the LEGO blocks.
  • 22. References …Learn more Angular Directives from Scratch Creating Custom Directives Comprehensive Directive API
  • 23. Thank You! This presentation was created specially for if058.Web-UI Group. Yaroslav Prodanchuk prepared by: