Create a custom directive in Angular JS

Angular Js uses MVW(Model View whatever) Architecture. We can create a dynamic pages using Angular Js. We can extend the HTML functionality using Angular JS directive method. We can extend the HTML with four types

  • Element – <my-dir></my-dir>
  • Attribute – <div my-dir=”example”></div>
  • CSS – <div class=”my-dir”></div>
  • Comment

$compile method match the directives based on element, attribute, CSS and comment. Below code will restrict Attribute, Element and CSS

  • ‘A’ – only matches attribute name
  • ‘E’ – only matches element name
  • ‘C’ – only matches class name
  • ‘M’ – only matches comment

We can add the restrict as AEC in the directive

Script.js

angular.module(‘myDirective’, [])
.controller('Controller', ['$scope', function($scope) {
  $scope.student = {
    name: 'Foo',
    age: '16'
  };
}])
.directive('myDir', function() {
  return {
    restrict: 'AEC',
    templateUrl: 'my-directive.html'
  };
});

index.html

<div ng-controller="Controller">
  <my-dir></my-dir>
</div>

my-dir.html

Name: {{student.name}} 
Age: {{student.age}}

Result :

Name: Foo
Age: 16

About the author: ShareSoftAdmin

Leave a Reply

Your email address will not be published.