0

I've just started out with AngularJs and am experimenting with directives. From what I've read, these can be defined in HTML using either:

  • A custom tag
  • An attribute
  • A class

<my-element></my-element>
<div my-element></div>
<div class="my-element"></div>

Many resources suggest using an attribute as it's the most compatible. I prefer the custom tag approach. Thankfully I only have to support modern browsers (IE10+). With this in mind, are there any other reasons why I should still use the attribute approach over a custom tag?

Any reasons welcome; compatibility, flexibility, etc.

2 Answers 2

3

There's actually no reason why you should use the attribute approach over a custom tag, when your use case actually requires a custom tag.

In Angular you are actually able to register directives not only as attributes, classes or elements, but also as comments (restrict: 'M'). Or if you want to, you directive could be used as attribute, class, element or comment without being restricted to just one type (restrict: 'AECM').

However, to answer your question, it's not that one should use the attribute approach over another one. It always depends on your use case. If you want to extend an existing element, it makes sense to use the attribute restriction (which is also the default by the way). If you want to build a reusable component, like e.g. a <tabs> element, you would rather go with the element restriction, because this is what you want then.

There could also be cases where you build directives, that are elements and being extended with other directives that are attributes.

So chose what works best (and makes most sense) for your use case.

Sign up to request clarification or add additional context in comments.

Comments

1

If tomorrow html decides to extend and incorporate an html tag using the same name as yours, that would be an issue, and although you might think you could have the same problem using attrs, the impact on the html rendering would not be the same, also, some other browsers might exhibit the same behavior as IE in a future for some reason, and decide not to accept or render custom tags. I just think attrs are a safer choice, but as for now, I know no reason why would you choose one over the other, other than creating sticking to the html standard tags

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.