While it's cool to make a custom element like we did in the previous lesson, it's actually more common to do things like create custom attributes. These attributes are going to add things like behaviors, and we can do so by using restrict "A". "A" is for attribute, "E" is for element. You can then provide a linking function, which is where you will put whatever the behavior is. We're just going to alert "Howdy!" to the user.
angular.module('greetings', [])
.directive("welcome", function() {
return {
restrict: "A",
link: function(){
alert("Howdy!");
}
}
});
From here, instead of having welcome as an element, let's do a div with welcome as an attribute:
<body ng-app="greetings">
<div welcome></div>
</body>
Now if we refresh, you'll see the alert saying "Howdy!". Another restriction we can use is "C" for class. If we change restrict to "C" and refresh without changing anything, we can see that nothing happens. We need to change the directive from an attribute to a class of the div.
<body ng-app="greetings">
<div class="welcome"></div>
</body>
If we refresh now, we'll see "Howdy!" alerted again. The last restriction is "M" for comment. If we change restrict to "M" and create a comment starting with "directive:" and then the name of our directive, refresh, and we'll see that it works again.
<body ng-app="greetings">
<!-- directive: welcome -->
</body>
The "M" restriction is used the least often, usually only for backwards compatibility and for passing markup validations. Typically it's best to add behaviors in attributes so you can stack them.
We'll create another attribute directive, call it "goodbye" and set the linking function to alert "See ya later!" and change the "welcome" directive's restriction back to "A"
angular.module('greetings', [])
.directive("welcome", function() {
return {
restrict: "A",
link: function(){
alert("Howdy!");
}
}
})
.directive("goodbye", function() {
return {
restrict: "A",
link: function(){
alert("See ya later!");
}
}
});
Now we should have a div with both "welcome" and "goodbye" as attributes
<body ng-app="greetings">
<div welcome goodbye></div>
</body>
If we refresh, we'll see "Howdy!" and then "See ya later!"
To recap: "E" is for element, "A" is for attribute, "C" is for class, and "M" is for comment. Attributes are going to be the main ones as far as adding behaviors that get used the most. If you don't specify the restrict property it will default to "A"