Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS - is it possible to have underscore in directive's name?


I have problem with angular directive's naming convention and the way angular normalize my directives names.
In order to follow some naming conventions in an existing project, to which I want to add angular, I need to name my custom directive with "_" in such manner:

app.directive("directive_name", function(...) {...});

Sadly doing so seems to contradict with Angular's way of normalization of directive's name and as a result such directives are ignored, not compiled and hence not shown on the screen.

[Question]
Is it possible to name a directive in such way that later we can use it in the HTML as follows:

<body>
    ...
    <my_directive></my_directive>
</body>

Thank you for your time and help!

like image 287
Milen Igrachev Avatar asked Dec 05 '22 06:12

Milen Igrachev


2 Answers

Yes it is possible, but you need declare it in camelCase:

app.directive("directiveName", function(...) {...});

html

<my_directive></my_directive>

but imho - better, use dashes

<my-directive></my-directive>

Actually angular will normalize directive names from html as following:

  1. Strip x- and data- from the front of the element/attributes.
  2. Convert the :, -, or _-delimited name to camelCase.
like image 58
Bogdan Savluk Avatar answered Jan 06 '23 08:01

Bogdan Savluk


you can have low dash on your directive name, you just have to write your directive name like always:

app.directive("yourDirectiveName", function(...) {...});

and than only in your code use the low dash:

<your_directive_name></your_directive_name>

Maybe depends on the version of angularjs you are using but the match between your html tag name and the directive name is made by the jqLite function camelCase

https://github.com/angular/angular.js/blob/v1.0.x/src/jqLite.js#L106

as you can see you can use low dash because of the regexp used:

SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g;
like image 43
markov00 Avatar answered Jan 06 '23 08:01

markov00