AngularJS | Create Directives
AngularJS | Create Directives http://www.shanidkv.com/
by Shanid
HTML
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<div class="wrapper" ng-app="shanidApp">
<h4>Types of Directives</h4>
<div class="panel panel-default">
<div class="panel-heading">HTML Element</div>
<div class="panel-body">
<main-dir model-name="Model" name="FieldName"></main-dir>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading">HTML Attribute</div>
<div class="panel-body">
<div main-dir2></div>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading">HTML Class</div>
<div class="panel-body">
<div class="main-dir3">Dir Class</div>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading">HTML Comment</div>
<div class="panel-body">
<!-- directive: main-dir4 -->
</div>
</div>
</div>
CSS
.wrapper{
padding: 20px;
}
JavaScript
var app = angular.module('shanidApp',[]);
app.controller('mainCtrl',['$scope', function($scope){
function initialize(){
// Initialize here
}
initialize();
}]);
// Create a directive and restricted to HTML element
app.directive('mainDir',function(){
return{
restrict: 'E',
scope:{
name: '@',
modelName: '='
},
replace: 'true',
template: '<div class="control-group">'+
'<label>Name</label>' +
'<input class="form-control" model="model"/>' +
'</div>'
}
});
// Create a directive and restricted to attribute
app.directive('mainDir2',function(){
return{
restrict: 'A',
replace: 'true',
template: '<p>Attribute Directive</p>'
}
});
// Create a directive and restricted to HTML class
app.directive('mainDir3',function(){
return{
restrict: 'C',
replace: 'true',
template: '<p>Class Directive</p>'
}
});
// Create a directive and restricted to HTML comment
app.directive('mainDir4',function(){
return{
restrict: 'M',
replace: 'false',
template: '<p>Comment Directive</p>'
}
});