Angular Custom Directive with example


Today I’m gonna explain Directives a little bit here. I’d like to think of Directives as a function that we run on a particular DOM element. ain’t cool to have provide extra functionality on an element. For example, the ng-click directive gives an element (could be a button, link or anything else) the ability to listen for the click event and run an Angular method when it receives the event. Directives are what makes the Angular framework so powerful, and, as you might already know, we do get to create custom ones as well. here is an example of a custom directive where I’ve created several HTML wrapper and a custom directive. the directive is introduced in form of an attribute of a <div> tag. take a look at the results and you’d understand how it works, easy :).

<!doctype html>
<html ng-app="myApp">
 <script src=""></script>
 <div ng-app="myApp" ng-init=" someProperty= 'some data'"></div>
 <div ng-init="siblingProperty= 'more data'">
 Inside Div Two: {{ myFirstProperty }}
 <div ng-init="myFirstProperty = 'data for 3rd property'" ng-controller="MyFirstCtrl">
 Inside Div Three: {{ myFirstProperty }}
 <div ng-controller="MyCtrl">
 Inside Div Four: {{ myFirstProperty }}
 Outside myDirective: {{ myProperty }}
 <div my-directive ng-init="myProperty = 'data inside property'">
 Inside myDirective: {{ myProperty }}
<script src="app.js"><script>

and in your app.js file:

angular.module('myApp', [])
 .controller('MyFirstCtrl', function($scope) {
 // we can leave it empty, it just needs to be defined
 .controller('MyCtrl', function($scope) {
 // lets leave it empty
 .directive('myDirective', function() {
 return {
 restrict: 'A',
 scope: true
Ramin Ahmadi
I am a full-stack front end developer with over 5 years experience in web design and development. I have worked with a wide variety of environments and languages including Angular, TypeScript, NodeJS, Restful API, Microservices, Atomic design, JQuery, Material design, Progressive Web Apps, DevOps, and many Azure tools. I make it a goal to automate myself out of routine tasks in my daily work. My motto is, ‘write human readable code, lean and clean’.

Comments 0

Your email address will not be published. Required fields are marked *

Angular Custom Directive with example

log in


reset password

Back to
log in
Font Resize
Choose A Format
Trivia quiz
Series of questions with right and wrong answers that intends to check knowledge
Voting to make decisions or determine opinions
The Classic Internet Listicles
Photo or GIF
GIF format