SlideShare uma empresa Scribd logo
1 de 10
Introduction to Directives 
Before introducing Directives , we should know brief about HTML.As web developers, we’re all 
familiar with HTML. Let’s take a moment to review and synchronize. Our terminology around 
this most fundamental of web technologies. 
HTML Document 
An HTML document is a plain text document that contains structure and may be styled through 
CSS or manipulated with JavaScript. 
HTML Node 
An HTML node is an element or chunk of text nested inside another element. All elements are 
also nodes; however, a text node is not an element. 
HTML Element 
An element comprises an opening tag and a closing tag. 
HTML Tag 
An HTML tag is responsible for marking the beginning and end of an element. A tag itself is 
declared using angle brackets. 
An opening tag contains a name that becomes the name of the element. It can also contain 
attributes, which decorate the element. 
Attributes 
To provide additional information about an element, HTML elements can contain attributes. 
These attributes are always set in the opening tag. We can set them in a key-value pair, like 
key="value", or as only a key. 
<a href="http://interviewGuly.com">Click me to go to InterviewGully</a> 
The <a> tag defines a link between another page on our site or off our site, depending on the 
contents of the href attribute, which defines the link’s destination. 
In summary, we can say that attributes add some behaviors in HTML element. 
What is a directive? 
Directive is used to provide extra functionality on the HTML element. 
For instance, the ng-click directive gives an element the ability to listen for the click event and 
run an Angular expression when it receives the event. 
Directives are what makes the Angular framework so powerful, and, as we’ve seen, we can also 
create them. 
A directive is defined using the .directive() method, one of the many methods available on our 
applications Angular module. 
The directive() method takes two arguments: 
name (string) 
The name of the directive as a string that we’ll refer to inside of our views.
factory_function (function) 
The factory function returns an object that defines how the directive behaves. It is expected to 
return an object providing options that tell the $compile service how the directive should 
behave when it is invoked in the DOM. 
In Angularjs, The HTML attributes and binding controls are called directives. 
All HTML attributes attached with prefix "ng-". The directives are 
Basic Directives 
1. ng-app : nitializes to application 
2. ng-init : initialize to application data 
3. ng-model : binds HTML controls to application data 
4. ng-Controller : Attached a controller class to view. 
Others then basic Directives 
1. ng-repeat : bind to repeated an HTML elements 
2. ng-if : bind an HTML elements with condition 
3. ng-grid : bind data collection to an HTML elements 
4. ng-show : Used to Show the HTML elements 
5. ng-hide : Used to Hide the HTML elements 
6. ng-class : CSS binding class 
7. ng-src : Used to pass the URL image etc. 
8. ng-switch 
9. ng-bind etc. 
Event Listener Directives 
1. ng-click : This is a click event to bind on HTML elements 
2. ng-dbl-click 
3. ng-mousedown 
4. ng-mouseup 
5. ng-mouseenter 
6. ng-mouseleave 
7. ng-mousemove 
8. ng-mouseover 
9. ng-keydown 
10. ng-keyup
11. ng-keypress 
12. ng-change 
Types of Directive 
1. Element directives 
2. Attribute directives 
3. CSS class directives 
4. Comment directives 
The possible options are shown below 
angular.module(‘IG’, []) 
.directive('myDirect ive', function() { 
return { 
restrict: String, 
priority: Number, 
terminal: Boolean, 
template: String or Template Function: 
function(tElement, tAttrs) (...}, 
templateUrl: String, 
replace: Boolean or String, 
scope: Boolean or Object, 
transclude: Boolean, 
controller: String or 
function(scope, element, attrs, transclude, otherInjectables) { ... }, 
controllerAs: String, 
require: String, 
link: function(scope, iElement, iAttrs) { ... }, 
compile: return an Object OR 
function(tElement, tAttrs, transclude) { 
return { 
pre: function(scope, iElement, iAttrs, controller) { ... }, 
post: function(scope, iElement, iAttrs, controller) { ... } 
} 
// or
return function postLink(...) { ... } 
} 
}; 
}); 
We can also return a function instead of an object to handle this directive definition, but it is 
best practice to return an object as we’ve done above. When a function is returned, it is often 
referred to as the postLink function, which allows us to define the link function for the 
directive. Returning a function instead of an object limits us to a narrow ability to customize our 
directive and, thus, is good for only simple directives. 
Bootstrapped HTML 
When the browser loads our HTML page along with Angular, we only need one snippet of code 
to boot our Angular application (we learned about it in the introductory chapter). 
In our HTML we need to mark up the root of our app using the built in directive ng-app. This 
Directive is meant to be used as an attribute; thus, we could stick it anywhere, but let’s choose 
the opening <html> tag. 
<!DOCTYPE html> 
<html ng-app="IG"> 
<head lang="en"> 
</head> 
<body> 
</body> 
</html> 
Our First Custom Directive 
The quickest way to get our feet wet is to just dive right in. Let’s go ahead and create a very 
basic custom directive. Consider the following HTML element, which we’ll define in a moment: 
<my-directive></my-directive> 
Provided we’ve created an HTML document and included Angular as well as the ng-app 
directive in the DOM to mark the root of our app, when Angular compiles our HTML, it will 
invoke this directive. 
The myDirective directive definition looks like: 
var app = angular.module('IG', []) 
app.directive('myDirective', function() { 
return { 
restrict: 'E', 
replace: true,
template: '<a href="http://interviewgully.com">Click me to go to 
InterviewGully</a>' 
} 
}); 
<!DOCTYPE html> 
<html ng-app="IG"> 
<head lang="en"> 
<meta charset="UTF-8"> 
<title>Directives in AngularJS</title> 
<script 
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.js"> 
</script> 
<script src="Scripts/external.js"></script> 
</head> 
<body> 
<my-directive></my-directive> 
</body> 
</html> 
Simple directive in action With the .directive() method, provided by the Angular module API, we 
can register new directives by providing a name as a string and function. The name of the 
directive should always be pascalCased, and the function we provide should return an object. 
Passing Data into a Directive 
Let’s recall our directive definition: 
app.directive('myDirective', function() { 
return { 
restrict: 'E', 
replace: true, 
template: '<a href="http://interviewgully.com">Click me to go to 
InterviewGully</a>' 
} 
}); 
Notice that in our template we are hard coding the URL and the text of our link: 
template: '<a href="http://interviewgully.com">Click me to go to InterviewGully</a>' 
With Angular, we aren’t limited to hard coding strings in the template of our directive. 
We can provide a nicer experience for others using our directive if we specify the URL and link 
Text without messing with the internal guts of the directive. Our goal here is to pay attention to 
the public interface of our directive, just as we would in any programming language. In essence, 
we’d like to turn the above template string into one that takes two variables: one for the URL 
and one for the link’s text: 
template: '<a href="{{myUrl}}">{{myLink}}</a>'
Looking at our main HTML document, we can declare our directive with attributes that will 
become the properties myUrl and mylink, set on the inner scope of our directive: 
<Div my-directive my-Url="http://interviewgully.com" my-Link= "Click me to go to 
InterviewGully" > </Div> 
Reload the page and notice that the div where we declared our directive has been replaced by 
its template; however, the links href is empty, and there is no text inside the brackets. 
<!DOCTYPE html> 
<html ng-app="IG"> 
<head lang="en"> 
<meta charset="UTF-8"> 
<title>Directives in AngularJS</title> 
<script src="Scripts/Vendor/angular.js"></script> 
<script src="Scripts/external.js"></script> 
</head> 
<body ng-controller="FirstController"> 
<!--<my-directive></my-directive>--> 
<my-directive my-url="www.interviewgully.com" my-link= "ClickInterviewGully" ></my-directive> 
</body> 
</html> 
//defining module 
var app = angular.module('IG', []) 
app.directive('myDirective', function() { 
"use strict"; 
return { 
restrict: 'EA', 
template: '<a></a>', 
link: function (scope, element, attr, ctrl) { 
var myUrl, myLink, handler;
handler = element.find('a')[0]; 
console.log(attr); 
handler.style.backgroundColor = "Red"; 
handler.setAttribute("href", attr.myUrl); 
handler.setAttribute("title", attr.myLink); 
handler.innerHTML = attr.myLink; 
} 
} 
}); 
Isolate Scope 
Isolate scope is the most confusing of the three options available when setting the scope 
Property, but also the most powerful. Isolate scope is based on the ideology present in Object 
Oriented Programming and design principles like SOLID have found their way into Angular via 
directives that use isolate scope. 
The main reason for isolation is to increase reusability. 
To create a directive with isolate scope we’ll need to set the scope property of the directive to 
an empty object, {}. Once we’ve done that, no outer scope is available in the template of the 
directive. 
app.directive('myDirective', function() { 
"use strict"; 
return { 
restrict: 'EA', 
scope: { 
}, 
template: '<div>{{fullname}}</div>', 
link: function(scope,element,attr,ctrl){ 
scope.fullname = attr.fullname; 
} 
} 
}); 
There are three types of isolate scope binding methods in Angularjs. 
1. @ 
2. = 
3. & 
1. Use of @  it accept only string value and provide one way binding (UI to Directive). 
This operator is used for reading an attribute 
<!DOCTYPE html>
<html ng-app="IG"> 
<head lang="en"> 
<meta charset="UTF-8"> 
<title>Directives in AngularJS</title> 
<script src="Scripts/Vendor/angular.js"></script> 
<script src="Scripts/external.js"></script> 
</head> 
<body ng-controller="FirstController"> 
<!--<my-directive></my-directive>--> 
<my-directive fullname="Brajesh Kumar Yadav" ></my-directive> 
</body> 
</html> 
//defining module 
var app = angular.module('IG', []) 
app.directive('myDirective', function() { 
"use strict"; 
return { 
restrict: 'EA', 
scope: { 
}, 
template: '<div>{{fullname}}</div>', 
link: function(scope,element,attr,ctrl){ 
scope.fullname = attr.fullname; 
} 
} 
}); 
app.controller('FirstController',['$scope', function($scope){ 
}]) 
Instead of the above code we use to optimized as below 
app.directive('myDirective', function() { 
"use strict"; 
return { 
restrict: 'EA', 
scope: { 
fullname : '@' 
}, 
template: '<div>{{fullname}}</div>' 
} 
}); 
2. Use of =  It work with object instead of string and provide two way binding (UI to 
Directive and directive to UI).
<!DOCTYPE html> 
<html ng-app="IG"> 
<head lang="en"> 
<meta charset="UTF-8"> 
<title>Directives in AngularJS</title> 
<script src="Scripts/Vendor/angular.js"></script> 
<script src="Scripts/external.js"></script> 
</head> 
<body ng-controller="FirstController"> 
<!--<my-directive></my-directive>--> 
ctrl <br> 
<input type="text" ng-model="Name" /> 
<br><br><br> 
directive <br> 
<my-directive fullname=Name ></my-directive> 
</body> 
</html> 
//defining module 
var app = angular.module('IG', []) 
app.directive('myDirective', function() { 
"use strict"; 
return { 
restrict: 'EA', 
scope: { 
fullname : '=' 
}, 
template: '<div><input type="text" ng-model="fullname" /></div>' 
} 
}); 
app.controller('FirstController',['$scope', function($scope){ 
$scope.Name = "InterviewGully"; 
}]) 
3. Use of &  It is use to invoke an expression or you can say evaluate expression. This 
operator is used to make a call on controller scope 
<!DOCTYPE html> 
<html ng-app="IG"> 
<head lang="en"> 
<meta charset="UTF-8"> 
<title>Directives in AngularJS</title> 
<script src="Scripts/Vendor/angular.js"></script> 
<script src="Scripts/external.js"></script> 
</head> 
<body ng-controller="FirstController"> 
<!--<my-directive></my-directive>-->
<my-directive clickhere="clickMe()" ></my-directive> 
</body> 
</html> 
//defining module 
var app = angular.module('IG', []) 
app.directive('myDirective', function() { 
"use strict"; 
return { 
restrict: 'EA', 
scope: { 
clickhere : '&' 
}, 
template: '<div ng-click="clickhere()">InterviewGully</div>' 
} 
}); 
app.controller('FirstController',['$scope', function($scope){ 
$scope.clickMe = function() 
{ 
alert("Hi! Welcome"); 
} 
}])

Mais conteúdo relacionado

Mais procurados

Why angular js Framework
Why angular js Framework Why angular js Framework
Why angular js Framework Sakthi Bro
 
Angular js for beginners
Angular js for beginnersAngular js for beginners
Angular js for beginnersMunir Hoque
 
AngularJS: an introduction
AngularJS: an introductionAngularJS: an introduction
AngularJS: an introductionLuigi De Russis
 
Understanding angular js
Understanding angular jsUnderstanding angular js
Understanding angular jsAayush Shrestha
 
AngularJs Superheroic JavaScript MVW Framework Services by Miracle Studios
AngularJs Superheroic JavaScript MVW Framework Services by Miracle StudiosAngularJs Superheroic JavaScript MVW Framework Services by Miracle Studios
AngularJs Superheroic JavaScript MVW Framework Services by Miracle StudiosLearnimtactics
 
Introduction to AngularJS
Introduction to AngularJSIntroduction to AngularJS
Introduction to AngularJSDavid Parsons
 
Introduction of angular js
Introduction of angular jsIntroduction of angular js
Introduction of angular jsTamer Solieman
 
Angular JS - Introduction
Angular JS - IntroductionAngular JS - Introduction
Angular JS - IntroductionSagar Acharya
 
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 JSSimon Guest
 
Gettings started with the superheroic JavaScript library AngularJS
Gettings started with the superheroic JavaScript library AngularJSGettings started with the superheroic JavaScript library AngularJS
Gettings started with the superheroic JavaScript library AngularJSArmin Vieweg
 

Mais procurados (20)

Why angular js Framework
Why angular js Framework Why angular js Framework
Why angular js Framework
 
Angular js
Angular jsAngular js
Angular js
 
Angular js for beginners
Angular js for beginnersAngular js for beginners
Angular js for beginners
 
Introduction to AngularJS
Introduction to AngularJSIntroduction to AngularJS
Introduction to AngularJS
 
Angular js
Angular jsAngular js
Angular js
 
AngularJS: an introduction
AngularJS: an introductionAngularJS: an introduction
AngularJS: an introduction
 
Understanding angular js
Understanding angular jsUnderstanding angular js
Understanding angular js
 
AngularJs Superheroic JavaScript MVW Framework Services by Miracle Studios
AngularJs Superheroic JavaScript MVW Framework Services by Miracle StudiosAngularJs Superheroic JavaScript MVW Framework Services by Miracle Studios
AngularJs Superheroic JavaScript MVW Framework Services by Miracle Studios
 
Angular Js Basics
Angular Js BasicsAngular Js Basics
Angular Js Basics
 
Angular js
Angular jsAngular js
Angular js
 
Introduction to AngularJS
Introduction to AngularJSIntroduction to AngularJS
Introduction to AngularJS
 
Introduction of angular js
Introduction of angular jsIntroduction of angular js
Introduction of angular js
 
Introduction to Angularjs
Introduction to AngularjsIntroduction to Angularjs
Introduction to Angularjs
 
AngularJS
AngularJSAngularJS
AngularJS
 
AngularJS Best Practices
AngularJS Best PracticesAngularJS Best Practices
AngularJS Best Practices
 
Angular js
Angular jsAngular js
Angular js
 
Angular JS - Introduction
Angular JS - IntroductionAngular JS - Introduction
Angular JS - Introduction
 
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
 
Angularjs PPT
Angularjs PPTAngularjs PPT
Angularjs PPT
 
Gettings started with the superheroic JavaScript library AngularJS
Gettings started with the superheroic JavaScript library AngularJSGettings started with the superheroic JavaScript library AngularJS
Gettings started with the superheroic JavaScript library AngularJS
 

Semelhante a Introduction to Directives: A Guide to AngularJS Directives

Angular Js Get Started - Complete Course
Angular Js Get Started - Complete CourseAngular Js Get Started - Complete Course
Angular Js Get Started - Complete CourseEPAM Systems
 
introduction to Angularjs basics
introduction to Angularjs basicsintroduction to Angularjs basics
introduction to Angularjs basicsRavindra K
 
Angular js 1.3 presentation for fed nov 2014
Angular js 1.3 presentation for fed   nov 2014Angular js 1.3 presentation for fed   nov 2014
Angular js 1.3 presentation for fed nov 2014Sarah Hudson
 
One Weekend With AngularJS
One Weekend With AngularJSOne Weekend With AngularJS
One Weekend With AngularJSYashobanta Bai
 
AngularJs Workshop SDP December 28th 2014
AngularJs Workshop SDP December 28th 2014AngularJs Workshop SDP December 28th 2014
AngularJs Workshop SDP December 28th 2014Ran Wahle
 
AngularJS Fundamentals + WebAPI
AngularJS Fundamentals + WebAPIAngularJS Fundamentals + WebAPI
AngularJS Fundamentals + WebAPIEric Wise
 
Angular js interview question answer for fresher
Angular js interview question answer for fresherAngular js interview question answer for fresher
Angular js interview question answer for fresherRavi Bhadauria
 
Angular workshop - Full Development Guide
Angular workshop - Full Development GuideAngular workshop - Full Development Guide
Angular workshop - Full Development GuideNitin Giri
 
AngularJS Basics
AngularJS BasicsAngularJS Basics
AngularJS BasicsRavi Mone
 
Angular Interview Questions-PDF.pdf
Angular Interview Questions-PDF.pdfAngular Interview Questions-PDF.pdf
Angular Interview Questions-PDF.pdfJohnLeo57
 
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 startedStéphane Bégaudeau
 
AngularJS training - Day 1 - Basics: Why, What and basic features of AngularJS
AngularJS training - Day 1 - Basics: Why, What and basic features of AngularJSAngularJS training - Day 1 - Basics: Why, What and basic features of AngularJS
AngularJS training - Day 1 - Basics: Why, What and basic features of AngularJSmurtazahaveliwala
 
The Basics Angular JS
The Basics Angular JS The Basics Angular JS
The Basics Angular JS OrisysIndia
 

Semelhante a Introduction to Directives: A Guide to AngularJS Directives (20)

Angular Js Get Started - Complete Course
Angular Js Get Started - Complete CourseAngular Js Get Started - Complete Course
Angular Js Get Started - Complete Course
 
introduction to Angularjs basics
introduction to Angularjs basicsintroduction to Angularjs basics
introduction to Angularjs basics
 
Angular 2
Angular 2Angular 2
Angular 2
 
Angular js 1.3 presentation for fed nov 2014
Angular js 1.3 presentation for fed   nov 2014Angular js 1.3 presentation for fed   nov 2014
Angular js 1.3 presentation for fed nov 2014
 
One Weekend With AngularJS
One Weekend With AngularJSOne Weekend With AngularJS
One Weekend With AngularJS
 
Intro to AngularJs
Intro to AngularJsIntro to AngularJs
Intro to AngularJs
 
AngularJs Workshop SDP December 28th 2014
AngularJs Workshop SDP December 28th 2014AngularJs Workshop SDP December 28th 2014
AngularJs Workshop SDP December 28th 2014
 
AngularJS Fundamentals + WebAPI
AngularJS Fundamentals + WebAPIAngularJS Fundamentals + WebAPI
AngularJS Fundamentals + WebAPI
 
Starting with angular js
Starting with angular js Starting with angular js
Starting with angular js
 
AngularJS
AngularJSAngularJS
AngularJS
 
Angular js interview question answer for fresher
Angular js interview question answer for fresherAngular js interview question answer for fresher
Angular js interview question answer for fresher
 
Angular workshop - Full Development Guide
Angular workshop - Full Development GuideAngular workshop - Full Development Guide
Angular workshop - Full Development Guide
 
AngularJS Basics
AngularJS BasicsAngularJS Basics
AngularJS Basics
 
Angular Interview Questions-PDF.pdf
Angular Interview Questions-PDF.pdfAngular Interview Questions-PDF.pdf
Angular Interview Questions-PDF.pdf
 
Angular Basics.pptx
Angular Basics.pptxAngular Basics.pptx
Angular Basics.pptx
 
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
 
AngularJS training - Day 1 - Basics: Why, What and basic features of AngularJS
AngularJS training - Day 1 - Basics: Why, What and basic features of AngularJSAngularJS training - Day 1 - Basics: Why, What and basic features of AngularJS
AngularJS training - Day 1 - Basics: Why, What and basic features of AngularJS
 
The Basics Angular JS
The Basics Angular JS The Basics Angular JS
The Basics Angular JS
 
Angular js-crash-course
Angular js-crash-courseAngular js-crash-course
Angular js-crash-course
 

Último

Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...PsychoTech Services
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingTeacherCyreneCayanan
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfAyushMahapatra5
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 

Último (20)

Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 

Introduction to Directives: A Guide to AngularJS Directives

  • 1. Introduction to Directives Before introducing Directives , we should know brief about HTML.As web developers, we’re all familiar with HTML. Let’s take a moment to review and synchronize. Our terminology around this most fundamental of web technologies. HTML Document An HTML document is a plain text document that contains structure and may be styled through CSS or manipulated with JavaScript. HTML Node An HTML node is an element or chunk of text nested inside another element. All elements are also nodes; however, a text node is not an element. HTML Element An element comprises an opening tag and a closing tag. HTML Tag An HTML tag is responsible for marking the beginning and end of an element. A tag itself is declared using angle brackets. An opening tag contains a name that becomes the name of the element. It can also contain attributes, which decorate the element. Attributes To provide additional information about an element, HTML elements can contain attributes. These attributes are always set in the opening tag. We can set them in a key-value pair, like key="value", or as only a key. <a href="http://interviewGuly.com">Click me to go to InterviewGully</a> The <a> tag defines a link between another page on our site or off our site, depending on the contents of the href attribute, which defines the link’s destination. In summary, we can say that attributes add some behaviors in HTML element. What is a directive? Directive is used to provide extra functionality on the HTML element. For instance, the ng-click directive gives an element the ability to listen for the click event and run an Angular expression when it receives the event. Directives are what makes the Angular framework so powerful, and, as we’ve seen, we can also create them. A directive is defined using the .directive() method, one of the many methods available on our applications Angular module. The directive() method takes two arguments: name (string) The name of the directive as a string that we’ll refer to inside of our views.
  • 2. factory_function (function) The factory function returns an object that defines how the directive behaves. It is expected to return an object providing options that tell the $compile service how the directive should behave when it is invoked in the DOM. In Angularjs, The HTML attributes and binding controls are called directives. All HTML attributes attached with prefix "ng-". The directives are Basic Directives 1. ng-app : nitializes to application 2. ng-init : initialize to application data 3. ng-model : binds HTML controls to application data 4. ng-Controller : Attached a controller class to view. Others then basic Directives 1. ng-repeat : bind to repeated an HTML elements 2. ng-if : bind an HTML elements with condition 3. ng-grid : bind data collection to an HTML elements 4. ng-show : Used to Show the HTML elements 5. ng-hide : Used to Hide the HTML elements 6. ng-class : CSS binding class 7. ng-src : Used to pass the URL image etc. 8. ng-switch 9. ng-bind etc. Event Listener Directives 1. ng-click : This is a click event to bind on HTML elements 2. ng-dbl-click 3. ng-mousedown 4. ng-mouseup 5. ng-mouseenter 6. ng-mouseleave 7. ng-mousemove 8. ng-mouseover 9. ng-keydown 10. ng-keyup
  • 3. 11. ng-keypress 12. ng-change Types of Directive 1. Element directives 2. Attribute directives 3. CSS class directives 4. Comment directives The possible options are shown below angular.module(‘IG’, []) .directive('myDirect ive', function() { return { restrict: String, priority: Number, terminal: Boolean, template: String or Template Function: function(tElement, tAttrs) (...}, templateUrl: String, replace: Boolean or String, scope: Boolean or Object, transclude: Boolean, controller: String or function(scope, element, attrs, transclude, otherInjectables) { ... }, controllerAs: String, require: String, link: function(scope, iElement, iAttrs) { ... }, compile: return an Object OR function(tElement, tAttrs, transclude) { return { pre: function(scope, iElement, iAttrs, controller) { ... }, post: function(scope, iElement, iAttrs, controller) { ... } } // or
  • 4. return function postLink(...) { ... } } }; }); We can also return a function instead of an object to handle this directive definition, but it is best practice to return an object as we’ve done above. When a function is returned, it is often referred to as the postLink function, which allows us to define the link function for the directive. Returning a function instead of an object limits us to a narrow ability to customize our directive and, thus, is good for only simple directives. Bootstrapped HTML When the browser loads our HTML page along with Angular, we only need one snippet of code to boot our Angular application (we learned about it in the introductory chapter). In our HTML we need to mark up the root of our app using the built in directive ng-app. This Directive is meant to be used as an attribute; thus, we could stick it anywhere, but let’s choose the opening <html> tag. <!DOCTYPE html> <html ng-app="IG"> <head lang="en"> </head> <body> </body> </html> Our First Custom Directive The quickest way to get our feet wet is to just dive right in. Let’s go ahead and create a very basic custom directive. Consider the following HTML element, which we’ll define in a moment: <my-directive></my-directive> Provided we’ve created an HTML document and included Angular as well as the ng-app directive in the DOM to mark the root of our app, when Angular compiles our HTML, it will invoke this directive. The myDirective directive definition looks like: var app = angular.module('IG', []) app.directive('myDirective', function() { return { restrict: 'E', replace: true,
  • 5. template: '<a href="http://interviewgully.com">Click me to go to InterviewGully</a>' } }); <!DOCTYPE html> <html ng-app="IG"> <head lang="en"> <meta charset="UTF-8"> <title>Directives in AngularJS</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.js"> </script> <script src="Scripts/external.js"></script> </head> <body> <my-directive></my-directive> </body> </html> Simple directive in action With the .directive() method, provided by the Angular module API, we can register new directives by providing a name as a string and function. The name of the directive should always be pascalCased, and the function we provide should return an object. Passing Data into a Directive Let’s recall our directive definition: app.directive('myDirective', function() { return { restrict: 'E', replace: true, template: '<a href="http://interviewgully.com">Click me to go to InterviewGully</a>' } }); Notice that in our template we are hard coding the URL and the text of our link: template: '<a href="http://interviewgully.com">Click me to go to InterviewGully</a>' With Angular, we aren’t limited to hard coding strings in the template of our directive. We can provide a nicer experience for others using our directive if we specify the URL and link Text without messing with the internal guts of the directive. Our goal here is to pay attention to the public interface of our directive, just as we would in any programming language. In essence, we’d like to turn the above template string into one that takes two variables: one for the URL and one for the link’s text: template: '<a href="{{myUrl}}">{{myLink}}</a>'
  • 6. Looking at our main HTML document, we can declare our directive with attributes that will become the properties myUrl and mylink, set on the inner scope of our directive: <Div my-directive my-Url="http://interviewgully.com" my-Link= "Click me to go to InterviewGully" > </Div> Reload the page and notice that the div where we declared our directive has been replaced by its template; however, the links href is empty, and there is no text inside the brackets. <!DOCTYPE html> <html ng-app="IG"> <head lang="en"> <meta charset="UTF-8"> <title>Directives in AngularJS</title> <script src="Scripts/Vendor/angular.js"></script> <script src="Scripts/external.js"></script> </head> <body ng-controller="FirstController"> <!--<my-directive></my-directive>--> <my-directive my-url="www.interviewgully.com" my-link= "ClickInterviewGully" ></my-directive> </body> </html> //defining module var app = angular.module('IG', []) app.directive('myDirective', function() { "use strict"; return { restrict: 'EA', template: '<a></a>', link: function (scope, element, attr, ctrl) { var myUrl, myLink, handler;
  • 7. handler = element.find('a')[0]; console.log(attr); handler.style.backgroundColor = "Red"; handler.setAttribute("href", attr.myUrl); handler.setAttribute("title", attr.myLink); handler.innerHTML = attr.myLink; } } }); Isolate Scope Isolate scope is the most confusing of the three options available when setting the scope Property, but also the most powerful. Isolate scope is based on the ideology present in Object Oriented Programming and design principles like SOLID have found their way into Angular via directives that use isolate scope. The main reason for isolation is to increase reusability. To create a directive with isolate scope we’ll need to set the scope property of the directive to an empty object, {}. Once we’ve done that, no outer scope is available in the template of the directive. app.directive('myDirective', function() { "use strict"; return { restrict: 'EA', scope: { }, template: '<div>{{fullname}}</div>', link: function(scope,element,attr,ctrl){ scope.fullname = attr.fullname; } } }); There are three types of isolate scope binding methods in Angularjs. 1. @ 2. = 3. & 1. Use of @  it accept only string value and provide one way binding (UI to Directive). This operator is used for reading an attribute <!DOCTYPE html>
  • 8. <html ng-app="IG"> <head lang="en"> <meta charset="UTF-8"> <title>Directives in AngularJS</title> <script src="Scripts/Vendor/angular.js"></script> <script src="Scripts/external.js"></script> </head> <body ng-controller="FirstController"> <!--<my-directive></my-directive>--> <my-directive fullname="Brajesh Kumar Yadav" ></my-directive> </body> </html> //defining module var app = angular.module('IG', []) app.directive('myDirective', function() { "use strict"; return { restrict: 'EA', scope: { }, template: '<div>{{fullname}}</div>', link: function(scope,element,attr,ctrl){ scope.fullname = attr.fullname; } } }); app.controller('FirstController',['$scope', function($scope){ }]) Instead of the above code we use to optimized as below app.directive('myDirective', function() { "use strict"; return { restrict: 'EA', scope: { fullname : '@' }, template: '<div>{{fullname}}</div>' } }); 2. Use of =  It work with object instead of string and provide two way binding (UI to Directive and directive to UI).
  • 9. <!DOCTYPE html> <html ng-app="IG"> <head lang="en"> <meta charset="UTF-8"> <title>Directives in AngularJS</title> <script src="Scripts/Vendor/angular.js"></script> <script src="Scripts/external.js"></script> </head> <body ng-controller="FirstController"> <!--<my-directive></my-directive>--> ctrl <br> <input type="text" ng-model="Name" /> <br><br><br> directive <br> <my-directive fullname=Name ></my-directive> </body> </html> //defining module var app = angular.module('IG', []) app.directive('myDirective', function() { "use strict"; return { restrict: 'EA', scope: { fullname : '=' }, template: '<div><input type="text" ng-model="fullname" /></div>' } }); app.controller('FirstController',['$scope', function($scope){ $scope.Name = "InterviewGully"; }]) 3. Use of &  It is use to invoke an expression or you can say evaluate expression. This operator is used to make a call on controller scope <!DOCTYPE html> <html ng-app="IG"> <head lang="en"> <meta charset="UTF-8"> <title>Directives in AngularJS</title> <script src="Scripts/Vendor/angular.js"></script> <script src="Scripts/external.js"></script> </head> <body ng-controller="FirstController"> <!--<my-directive></my-directive>-->
  • 10. <my-directive clickhere="clickMe()" ></my-directive> </body> </html> //defining module var app = angular.module('IG', []) app.directive('myDirective', function() { "use strict"; return { restrict: 'EA', scope: { clickhere : '&' }, template: '<div ng-click="clickhere()">InterviewGully</div>' } }); app.controller('FirstController',['$scope', function($scope){ $scope.clickMe = function() { alert("Hi! Welcome"); } }])