AngularJS Directives - custom directives

AngularJS can be used to define custom directives to use in markup as element or attribute.

by Asif Sharif Shahid

HTML

<body ng-app="hello">
    <div ng-controller="CustomDirectiveController">
         <h3>Developing and using custom directives</h3>

         <h3>Very simple element</h3>

        <simple-element id="test">simple content</simple-element>
         <h3>Custom directive as attribute</h3>

        <div products-information class="custonColor">Product information</div>
         <h3>Custom directive as element</h3>

        <products-information class="custonColor">some product Information</products-information>
         <h3>DOM manipulation custom directive</h3>

        <div dom-modification-directive>Click Me!</div>
    </div>
</body>

CSS

#test
{
    color: red;
}
.custonColor
{
    color: green;
}

JavaScript

var app = angular.module("hello", []);

  app.directive('domModificationDirective', function () {
      return {
          link: function ($scope, element, attrs) {
              element.bind('click', function () {
                  element.html('Mouse Clicked!');
                  element.css('background-color', 'green');
              });
              element.bind('mouseenter', function () {
                  element.html('Mouse Entered!');
                  element.css('background-color', 'yellow');
              });
              element.bind('mouseleave', function () {
                  element.html('Mouse Leave the area!');
                  element.css('background-color', 'white');
              });
          }
      };
  });


  app.directive('productInformation', function () {
      return {
          restrict: 'EA',
          template: "Product : <div>{{product.device}}</div>" +
              "<div>{{product.manufacturer}}</div>" +
              "<div>{{product.purchaseDate}}</div>"
      };
  });

  app.directive('productsInformation', function () {
      return {
          restrict: 'EA',
          template: "<div ng-repeat='pr in products'>" +
              "<span>{{pr.device}}</span>, <span>{{pr.manufacturer}}</span>, " +
              "<span>{{pr.purchaseDate}}</span></div>"
      };
  });


  app.controller('CustomDirectiveController', ['$scope', function ($scope) {
      var counter = 0;
      $scope.product = {
          device: "Microphone",
          manufacturer: "Mydeo",
          purchaseDate: "07.09.2010"
      };

      $scope.products = [{
          device: "Speaker",
          manufacturer: "Tambee",
          purchaseDate: "07.01.2010"
      }, {
          device: "Printer",
          manufacturer: "Wordpedia",
          purchaseDate: "07.10.2014"
      }, {
          device: "Headsets",
          manufacturer: "Viva",
          purchaseDate: "27.04.2012"
      }];

      $scope.addProduct = function () {
          counter++;
        ...