admin管理员组

文章数量:1415119

I am trying to apply a condition to href or ng-href.

The condition is if email !== null

My code looks like this:

<a ng-attr-href="{{email !== null}}" href="mailto:{{email | lowercase}}">{{email | lowercase | nullValue}}</a>

This is evaluating to either href="true" or href="false".

This seems close to working, but I still get the href attribute being there if the value is null:

ng-attr-href="mailto:{{email !== null ? email: email | lowercase}}"

How do I remove the href entirely if the value from the data is null? Is it possible to wrap the entire condition around the html href attribute?

I am trying to apply a condition to href or ng-href.

The condition is if email !== null

My code looks like this:

<a ng-attr-href="{{email !== null}}" href="mailto:{{email | lowercase}}">{{email | lowercase | nullValue}}</a>

This is evaluating to either href="true" or href="false".

This seems close to working, but I still get the href attribute being there if the value is null:

ng-attr-href="mailto:{{email !== null ? email: email | lowercase}}"

How do I remove the href entirely if the value from the data is null? Is it possible to wrap the entire condition around the html href attribute?

Share Improve this question asked Sep 24, 2015 at 11:35 lharbylharby 3,2776 gold badges26 silver badges65 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

There are several ways of solving your problem. I prefer this:

<a ng-if="email !== null" href="mailto:{{email | lowercase}}">{{email | lowercase | nullValue}}</a>
<a ng-if="email == null">{{email | lowercase | nullValue}}</a>

You can easily wrap this into a directive if you need more plex conditions or attribute toggles.

You can also use something similar to your ng-attr-href as before but instead with only ng-href :

<a ng-href="{{email ? 'mailto:'+(email | lowercase) : ''}}">
{{email | lowercase | nullValue}}
</a>

While this would always create the ng-href attribute in the anchor tag, without an email it would be empty and would not create the href attribute. The end results would look like the following:

<a ng-href="mailto:tests" href="mailto:tests">tests</a>
<a ng-href></a>

本文标签: javascriptRemove href attribute if value is null in angularjsStack Overflow