lharby lharby - 3 months ago 35
Javascript Question

Remove href attribute if value is null in angularjs

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?

Answer

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 complex conditions or attribute toggles.