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

ADFS (1) ADO .Net (1) Ajax (1) Angular (43) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (47) CD (1) CI (2) CloudComputing (2) Coding (7) CQRS (1) CSS (2) Design_Pattern (6) DevOps (4) DI (3) Dotnet (8) DotnetCore (16) Entity Framework (2) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) Lamda (3) Linq (11) microservice (3) Mongodb (1) MVC (46) NodeJS (8) React (11) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (1) UI (1) UnitTest (1) WCF (14) Web Api (15) Web Service (1) XMl (1)

Dotnet Guru Archives