Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable angular trim on directive attribute

Currently writing a directive, and need to pass space as character to it. like:

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

Turns out that angular removes the leading space; but I want it preserved. Any way of doing that?

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

like image 220
ra00l Avatar asked Apr 17 '15 07:04

ra00l


1 Answers

I would do one of:

  1. Wrap the attribute in {{' and '}}:

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

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

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

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

    and then pass the value through $eval to get to the string including the space:

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

Note: directly accessing the attribute via the jQuery/jQlite attr function is ever so slightly not friendly to Angular supporting different formats of directives/attributes via normalization, and forces the users to the directive to use the one you access via attr.


BTW: Custom HTML elements should have the closing tag explicitly in the template. If you don't, I've found the DOM that the browser uses often isn't quite what is expected

like image 50
Michal Charemza Avatar answered Sep 29 '22 11:09

Michal Charemza