Sunday, October 22, 2017

Force angularjs attribute directive to not parse its value

I am making an attribute directive that will work similarly to ng-if.

window-match-media="(min-width: 400px)"

which will make the element render if the media query matches and disappear otherwise. I am modeling my directive on the code for ngIf

It works great with the exception that I have to currently enclose the media query in an extra pair of quotes. This is because without it, it seems to try to parse the attribute value. This makes sense for ngIf but in my case I want to simply treat the value as a string.

I see nothing in the ngIf codebase that would allow me to indicate that the value should not be parsed, and adding

  scope: {
    windowMatchMedia: '@',
  },

does not help (I’m not sure attribute directives can isolate scope anyways?).

I access the value via the $attributes parameter to the directive’s link function which always does seem to provide it as a string, but if I do not specifically make it one with quotes ie

window-match-media="'(min-width: 400px)'"

I get an error before my directive ever gets a chance to run due to the parsing issue. How do I tell the attribute directive to not parse its value? I don’t see anything about this in the $compile docs.

Edit: Here is a Plunkr demonstrating the issue. I should probably open source this after I get it working the way I want and document it

Note how in this example, there is an error in the console

If I surround the attribute in quotes it works because the parser is detecting it as a string. But I don’t want the parser involved at all. I want to write a regular ol’ attribute value.

I would like the attribute syntax in the first example to work.

Source: AngularJS



from Angular Questions https://angularquestions.com/2017/10/22/force-angularjs-attribute-directive-to-not-parse-its-value/
via @lzomedia #developer #freelance #web #lzomedia.com

No comments:

Post a Comment