Wednesday, March 30, 2016

Directives

Extending HTML with new attributes can be achieved with directives in Angular JS.

Basically 2 Types of Directives are available...
  1. Built in Directives
  2. Custom Directives
Some of Built In Directives are
  1. ng-app
  2. ng-init
  3. ng-model
  4. ng-change 
  5. ng-hide 
  6. ng-value 
  7. ng-disabled
  8. ng-repeat
Custom Directives

In addition to the Built In Angular JS directives, We can create our own directives with the help of the .directive function.

In Directives naming standards should be taken care. While declaring/Implementing the directive, We must use camel case name (directiveAttributeTest) but while invoking we must use - separator (directive-attribute-test)

Invoking a directives can by done in 4 ways
  • Element name (E)
  • Attribute (A)
  • Class (C)
  • Comment (M)
For better understanding look into the sample code below

<!DOCTYPE html>
<head>
    <title></title>
    <script src="angular.min.js"></script>
    <script>
        var app = angular.module("MyNgApp", []);

        app.directive("directiveAttributeTest", function () {
            return {
                restrict: "A",
                link: function () {
                    alert("Attribute  Test");
                }
            }
        });

        app.directive("directiveElementTest", function () {
            return {
                restrict: "E",
                link: function () {
                    alert("Element  Test");
                }
            }
        });

        app.directive("directiveCommentTest", function () {
            return {
                restrict: "M",
                link: function () {
                    alert("Comment test ");
                }
            }
        });

        app.directive("directiveClassTest", function () {
            return {
                restrict: "C",
                link: function () {
                    alert("Class Test");
                }
            }
        });

    </script>
</head>
<body ng-app="MyNgApp">
    <div directive-attribute-test></div>
    <div class="directive-class-test"></div>
     <directive-element-test></directive-element-test>
    <!-- directive: directive-comment-test -->
</body>
</html>