In previous posts, we learnt how to create a custom directive. Any custom directive can be either used as element or attribute.
<div my-custom></div>
.<my-custom></my-custom>
.However, a custom directive can also be used as class <div class="my-custom"></div>
. In order to restrict them to be used in certain ways, we can set restrict
properties. Here are the restrict values and their meaning.
In below code snippet, we have a controller and its $scope property set. Next, we are creating a directive named 'my-custom-restrict' (normalized name 'myCustomRestrict') where we are setting restrict
value as 'AEC' that means my-custom-restrict directive can be used either as "element", "attribute" or as "class attribute".
<script>
var app = angular.module("app", [])
.controller("CustomDirectiveController", function ($scope) {
$scope.username = "SheoNarayan";
$scope.address = "Hyderabad, India";
});
app.directive('myCustomRestrict', function () {
return {
restrict : 'AEC',
template: ' UserName: {{ username }}, Address: {{ address }}'
};
});
</script>
<div ng-app="app" ng-controller="CustomDirectiveController">
<h2>Restricting custom directive</h2>
<div><b>Attribute:</b> <span my-custom-restrict></span></div>
<div><b>Element:</b> <my-custom-restrict></my-custom-restrict></div>
<div><b>Class:</b> <span class="my-custom-restrict"></span></div>
</div>
In the HTML block, we are using my-custom-restrict directive in all three form (Attribute, Element and as Class attribute).
Output
Views: 13671 | Post Order: 37