Reputation: 1494
I'm trying to learn AngularJS from w3schools. For creating custom directives the below example has been provided at Custom Directives
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>
<body ng-app="myApp">
<w3-test-directive></w3-test-directive>
<script>
var app = angular.module("myApp", []);
app.directive("w3TestDirective", function() {
return {
template : "<h1>Made by a directive!</h1>"
};
});
</script>
</body>
Here the name of a directive is different in while creating it (w3TestDirective) and that used in HTML (w3-test-directive).
If I use HTML element as <w3TestDirective>
I see nothing in the output.
I see that AngularJS needs to perform attribute normalisation. However, I do not understand why AngularJS requires performing normalisation. Would someone help me understand the rationale behind AngularJS?
Upvotes: 2
Views: 387
Reputation: 18402
We typically refer to directives by their case-sensitive camelCase normalized name (e.g. ngModel). However, since HTML is case-insensitive, we refer to directives in the DOM by lower-case forms, typically using dash-delimited attributes on DOM elements (e.g. ng-model). See AngularJS Developer Guide - Directive Normalization. – georgeawg
Thanks to georgeawg, I could not explain it any better.
While using AngularJS 1.x
your have to configure restrict
which is in your case E
for element
. restict: 'E'
matches with your element tag <w3-test-directive></w3-test-directive>
.
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>
<body ng-app="myApp">
<w3-test-directive></w3-test-directive>
<script>
var app = angular.module("myApp", []);
app.directive("w3TestDirective", function() {
return {
restrict: 'E',
template : "<h1>Made by a directive!</h1>"
};
});
</script>
</body>
While using AngularJS 1.5+
restrict
is set to EA
by default which will match with the element
and the attribute
. restrict: 'EA'
matches with <w3-test-directive></w3-test-directive>
and <span w3-test-directive=""></span>
In that case your code works fine:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body ng-app="myApp">
<w3-test-directive></w3-test-directive>
<span w3-test-directive=""></span>
<script>
var app = angular.module("myApp", []);
app.directive("w3TestDirective", function() {
return {
template : "<h1>Made by a directive!</h1>"
};
});
</script>
</body>
Upvotes: 2
Reputation: 663
You nedd to add restrict: 'E', for using directive as a html element. See this :
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>
<body ng-app="myApp">
<w3-test-directive></w3-test-directive>
<script>
var app = angular.module("myApp", []);
app.directive("w3TestDirective", function() {
return {
restrict: 'E',
template : "<h1>Made by a directive!</h1>"
};
});
</script>
</body>
Upvotes: 1