AngularJS Basics: Custom Directives!

What is up, friends? I am back with day 4 of my 100 days of code! I feel like blogging what I have been learning has been super helpful to me. Not only do I get to prove to myself that I know what is going on but I also get to practice my technical writing!!

Today, we are going to learn about custom directives and restricting directives.

Photo by MIKHAIL VASILYEV on Unsplash

First, let’s chat about components and how they relate to directives.

Now, most web applications are made up of reusable components. Components are pieces of code that make up our website. For example, we would have a NavBar component, a header component, or a button component. In Angular, we create these components by using directives.

Directives can be HTML attributes and HTML elements, but most of our directives will be HTML elements.

Creating custom directives

As we’ve seen with services and controllers, we can use the .directive function to create our directives. Our directive names are what we will use to reference the DOM but keep in mind, the DOM is case-sensitive. If we have a directive named catDirective, it would become <cat-directive></cat-directive>.

Take a look at the example below:

As you can see, we return an object. This describes the functionality of our directive. We would call in like this in our dom: <cat-directive></cat-directive> and it would transform into this when it is rendered by angular!

Keep in mind, you can’t have multiple root elements in your template. If you want to have multiple root elements in your template, then we have to save each line of your template as a separate element in an array then .join all the elements together. You could also use the templateUrl method if your template gets too big!

Also, if you didn’t want <cat-directive> to be wrapping the <div>, you would just add another property called replace and you would set the value to true.

Restricting directives

Angular allows us to set a property called restrict. We can pass through a string of specific letters to tell Angular how our directive can be used. Here are the letters:

A - used as an attribute. E- used as an element. C- used as a class name. M- used as a comment. You can also put them together. So, if you used AE, it would allow the directive to be used as an element and an attribute. By default, restrict is set to AE. See the example below.

If restrict was set to “A” then we would only be able to use it as an attribute. Lines 13–16 show how you would use each one.

Super short and simple blog post today because I’ve been super busy! I hope this is helpful and makes your coding journey a little bit easier!