Resume
In this passage, we will talk about Directive and Controller.
Directive
First of all, we will concentrate on Directive. In AngularJS, we can create our own HTML Tag/Element name, Attribute and even Comment.
Create Tag/Element name
In the following codes, we can see how we can create our own HTML Tag/Element name.
<body ng-app="app">
<my-own-tag></my-own-tag>
<script>
angular.module("app",[]).directive("myOwnTag",function(){
return {
restrict : "E",
template : "<h1>Hello, World!</h1>"
};
});
</body>
The code above will show "Hello, World!" in h1 style
In this example, we can notice that, we have created a new HTML Tag/Element name, and appended a h1 DOM to <my-own-tag>
.
Secondly, even our tag is <my-own-tag>
, we should use myOwnTag
while binding our tag in AngularJS.
Attention: After appending an element to an Directive, we cannot append another element to the previous element using AngularJS
The following code DOESN’T work
var app = angular.module("app", []);
app.directive("my-own-tag", function () {
return {
restrict: "E",
template: "<title></title>",
}
});
app.directive("title", function () {
return {
restrict: "E",
template:"<h1>Title</h1>",
}
});
<h1>Title</h1>
Will be escaped and become <h1>Title</h1>
Restrict
Maybe some people have noticed that we have used restrict while returning. Well, in fact we can restrict our Directive to only be invoked by some of the methods.
We have 4 different property to do that.
restrict : "E"
for Element name / Tag
restrict : "A"
for Attribute
restrict : "C"
for Class
restrict : "M"
for Comment.
Also, we can have combined restriction such as:
restrict : "MC"
.
Others
We can also use the method above for other things.
<div my-own-attr></div my-own-attr>
<div class="my-own-class"></div class="my-own-class">
or even in comments
<!-- directive : my-own-comment -->
All these methods work and have the same effect as tag do.