最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Remove href attribute if value is null in angularjs - Stack Overflow

programmeradmin0浏览0评论

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>
发布评论

评论列表(0)

  1. 暂无评论