Here we are going to talk about creating custom directives in AngularJS. Here we will discuss about four type of custom directives. They are as following
1. 'E' -> Restricted to element.
2. 'A' -> Restricted to attribute.
3. 'C' -> Restricted to class.
4. 'M' -> Restricted to comment.
For every directive we have set a console text which you will find in your console tab in browser developer section after the page loads/ reloads..
We are going to write two program files. One is the script file myApp.js and another is the html file directives.html.
myApp.js
//------------------------------------------------------------------------------------------------------------------------
var app = angular.module('myApp',[]);
app.controller('myCtrl',function($scope){
$scope.data='Subhroneel'; //this is for some text in the custom tag
})
.directive('commentrestirict',function(){
return {
restrict:'M', //this is for comment directive
link:function(){
console.log('I am a comment');
}
};
})
.directive('classrestirict',function(){
return {
restrict:'C', // this is for class directive
link:function(){
console.log('I am a class');
}
};
})
.directive('elementrestirict',function(){
return {
restrict:'E', //this is for element directive
link:function(){
console.log('I am an element');
}
};
})
.directive('attributerestirict',function(){
return {
restrict:'A', //this is for attribute directive
link:function(){
console.log('I am an attribute');
}
};
});
//----------------------------------------------------------------------------------------------------------------------
directives.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link href="style.css" rel="stylesheet" />
<script src="https://code.angularjs.org/1.0.8/angular.js"></script>
<script src="app.js">
</script>
</head>
<body ng-app="myApp" ng-controller="myCtrl">
<p class="classrestirict" attributerestirict>Hello {{data}}</p>
<elementrestirict>Hello {{data}} this is an element</elementrestirict>
<!-- directive:commentrestirict -->
</body>
</html>
Below here you will find the demo, (sorry it does not work sometimes)
Hello {{data}}
No comments:
Post a Comment