AngularJS directives as “custom” HTML tags: isn

2019-07-21 07:50发布

I'm currently reading a lot about different JS frameworks (EmberJS, AngularJS, etc.).

On first sight, I loved AngularJS' idea of using directives like custom HTML tags:

<mytag>...</mytag>

But isn't this dangerous? If I define a lot of such tags, then there's a high likelihood that a future HTML spec may also define one of my custom tags, but with a whole other meaning!

I know that custom tags may be allowed by the HTML spec itself:

http://w3c.github.io/webcomponents/spec/custom/

But at the moment, it isn't. So is it good practice to use custom tags as directives? Or should I better rely on ng-xxx attributes?

3条回答
不美不萌又怎样
2楼-- · 2019-07-21 08:30

There is a small chance, yes. However, let's do some maths:

If your tag name is one letter long, there is a one in 26 chance of any one new tag having the same name.

If it is two letters long, there is a one in 26*26 chance.

In short, the chances of it happening are a few in 26^[number of letters in tag name]. Small. Given that the average tag name is 6 letters long in standard HTML, that's a one in 308915776 chance. And that's excluding your custom tags with dashes and all.

Furthermore, AngularJS is a Google project. Google are way ahead of the rest of us and if it looks like something like that's going to happen, they'll set a team on it and have a solution in hours if not less.

You don't need to worry about tag conflicts.

查看更多
贼婆χ
3楼-- · 2019-07-21 08:44

I think you're quite safe creating your own element directives. The risk of a future HTML tag coming out with the same name is quite low.

You can also namespace your directives, and this will significantly reduce the risk of any future naming conflicts.

Let's say that your app name is "MyApp", you could have something like this:

<ma-custom-tag></ma-custom-tag>

This also assists with avoiding conflicts in any angular modules you may add to your project. Most angular libraries that are released should have some namespacing.

The Angular project has a best practices Wiki that touches on this concept: https://github.com/angular/angular.js/wiki/Best-Practices

查看更多
女痞
4楼-- · 2019-07-21 08:44

Custom elements require a dash in its name. Native HTML tags don't have dashes (at least there's no existing one). In angular you can define directives with camel cased names which solves your worries too.

查看更多
登录 后发表回答