Custom Directives
Custom directives are used in AngularJS to extend the
functionality of HTML. Custom directives are defined using
"directive" function. A custom directive simply replaces the element
for which it is activated.
AngularJS provides support to create custom directives for
following type of elements.
Element directives
− Directive activates when a matching element is encountered.
Attribute − Directive activates when a matching attribute is encountered.
CSS − Directive activates when a matching css style is encountered.
Comment − Directive activates when a matching comment is encountered.
Attribute − Directive activates when a matching attribute is encountered.
CSS − Directive activates when a matching css style is encountered.
Comment − Directive activates when a matching comment is encountered.
Create New Directives
In addition to all the built-in AngularJS directives, you can
create your own directives.
New directives are created by using the .directive function.
New directives are created by using the .directive function.
To invoke the new directive, make an HTML element with the same tag name as the new directive.
When naming a directive, you must use a camel case name, w3TestDirective, but when invoking it, you must use - separated name, w3-test-directive:
<body ng-app="myApp">
<w3-test-directive></w3-test-directive>
<script>
var app = angular.module("myApp", []);
app.directive("w3TestDirective", function() {
return {
template : "<h1>Made by a directive!</h1>"
};
});
</script>
</body>
You can invoke a directive by using:
Element name
Attribute
Class
Comment
Attribute
Class
Comment
The examples below will all produce the same result:
Element name
<w3-test-directive></w3-test-directive>
<w3-test-directive></w3-test-directive>
Attribute
<div w3-test-directive></div>
<div w3-test-directive></div>
Class
<div class="w3-test-directive"></div>
<div class="w3-test-directive"></div>
Comment
<!-- directive: w3-test-directive -->
<!-- directive: w3-test-directive -->
Restrictions
You can restrict your directives to only be invoked by some of
the methods.
Example
By adding a restrict property with the value "A",
the directive can only be invoked by attributes:
var app = angular.module("myApp", []);
app.directive("w3TestDirective", function() {
return {
restrict : "A",
template : "<h1>Made by a directive!</h1>"
};
});
The legal restrict values are:
E for Element name
A for Attribute
C for Class
M for Comment
A for Attribute
C for Class
M for Comment
By default the value is EA, meaning that both Element names
and attribute names can invoke the directive.
0 comments:
Post a Comment