superman-directive.js
angular.module('myApp', [])
.directive('superman', function() {
return {
// restricts how the directive can be used
restrict: 'E',
templateUrl: 'superman-template.html',
controller: function() {
this.message = "I'm superman!"
},
controllerAs: 'supermanCtrl',
// Executed after Angular's initialization. Use commonly
// for adding event handlers and DOM manipulation
link: function(scope, element, attributes) {
element.on('click', function() {
alert('I am superman!')
});
}
}
});
superman-template.html
<h2>{{supermanCtrl.message}}</h2>
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="/?originalUrl=https%3A%2F%2Friptutorial.com%2F%26quot%3Bhttps%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.5.0%2Fangular.js%26quot%3B%26gt%3B%26lt%3B%2Fscript%26gt%3B%2520%2520%26lt%3Bscript%2520src%3D%26quot%3Bsuperman-directive.js%26quot%3B%26gt%3B%26lt%3Bscript%2F%26gt%3B%26lt%3B%2Fhead%26gt%3B%26lt%3Bbody%26gt%3B%26lt%3Bdiv%2520ng-app%3D%26quot%3BmyApp%26quot%3B%26gt%3B%2520%2520%26lt%3Bsuperman%26gt%3B%26lt%3B%2Fsuperman%26gt%3B%26lt%3B%2Fdiv%26gt%3B%26lt%3B%2Fbody%26gt%3B%26lt%3B%2Fhtml%26gt%3B%253C%2Fcode">
You can check out more about directive's restrict and link functions on AngularJS's official documentation on Directives