Disable angular attribute attribute trimming

The directive is currently written, and you need to pass a space as a character. as:

<my-directive exclude-chars=" abc"/>

It turns out that angular removes the leading space; but I want it to be preserved. Any way to do this?

EDIT: I pass the directive parameter as a string (using @, not as a variable, using =)

+5
source share
2 answers

I would do one of:

  • Wrap the attribute in {{' and '}} :

     <my-directive exclude-chars="{{' abc'}}"></my-directive> 

    and access the abc line, including the space, using attrs.excludeChars in the link function of the directive

     link: function(scope, element, attrs) { var excludeChars = attrs.excludeChars; } 
  • Wrap the attribute in ' and ' :

     <my-directive exclude-chars="' abc'"></my-directive> 

    and then pass the value through $eval to go to the line containing the space:

     link: function(scope, element, attrs) { var excludeChars = scope.$eval(attrs.excludeChars); } 

Note: direct access to an attribute using the jQuery / jQlite attr function is always a bit not Angular friendly, supporting various directive / attribute formats with normalization and forces users to use the directive that you access through attr .


BTW: Custom HTML elements must have a private tag explicitly in the template. If you do not, I found a DOM that often uses a browser, not quite what is expected

+8
source

One of the easiest solutions is to use the jqlite attr function, such as the code below.

In your directive code.

 link: function(scope, element, attrs){ console.log('>'+element.attr("exclude-chars")); } 

The jsfiddle demo is here.

+1
source

All Articles