Thursday, 7 April 2016

Custom Directives- AngularJS

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.

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.

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

The examples below will all produce the same result:

Element name
<w3-test-directive></w3-test-directive>

Attribute
<div w3-test-directive></div>

Class
<div class="w3-test-directive"></div>

Comment
<!-- 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

By default the value is EA, meaning that both Element names and attribute names can invoke the directive.



0 comments:

Post a Comment

Topics

ADO .Net (2) Ajax (1) Angular Js (17) Angular2 (24) ASP .Net (14) Azure (1) Breeze.js (1) C# (49) CloudComputing (1) CMS (1) CSS (2) Design_Pattern (3) DI (3) Dotnet (21) Entity Framework (3) ExpressJS (4) Html (3) IIS (1) Javascript (6) Jquery (9) Lamda (3) Linq (11) Mongodb (1) MVC (48) NodeJS (7) RDLC (1) Report (1) Sql Server (29) SSIS (3) SSRS (2) UI (1) WCF (12) Web Api (10) Web Service (1) XMl (1)