4

I have some links created with angular material. In there for links and buttons we us <md-button>. Now I have a link and I need to add the href attribute to it only if the url is present. Otherwise it should not have a href.

The reason is, I have main links and sub-links underneath. Main links which have sub-links can't have an href. If it does have at least and empty href, as soon as I click it to expand the sub-links, it will take me to the index template. There are main links which don't have any sub-links. So, for them I need the href and for the links with sub-links I need to completely remove the href. How can I do this?

hansmaad
  • 18,417
  • 9
  • 53
  • 94
THpubs
  • 7,804
  • 16
  • 68
  • 143
  • 1
    `ngHref` maybe able to help you here. I think if the expression provided to `ngHref` is null it does not render\removes the tag. Try it. – Chandermani Jul 06 '15 at 05:54
  • 1
    possible duplicate of [What is the best way to conditionally apply attributes in Angular?](http://stackoverflow.com/questions/15696416/what-is-the-best-way-to-conditionally-apply-attributes-in-angular) – mido Jul 06 '15 at 05:58
  • @mido22 Nope.. In there it shows how to add the attribute value conditionally. What I want is to add the whole attribute conditionally – THpubs Jul 06 '15 at 09:40

3 Answers3

9

I am not an expert in angular, but if I am correct, for Angular 1.3 and above:

<a ng-attr-href="{{href || undefined}}">Hello World</a>

for the versions below 1.3, I guess you can do:

<a ng-if="href" ng-attr-href="{{href}}">Hello World</a>
<a ng-if="!href" >Hello World</a>

personally, I do not like the second method because it leads to code duplication.

answer taken from this post

Community
  • 1
  • 1
mido
  • 24,198
  • 15
  • 92
  • 117
1

You can add the href attribute in the directive's link function

return {
  scope : {
    link : '=myLink'
  },
  link: function(scope, elem) {
    if (scope.link.url) {
      elem.attr('href', scope.link.url);
    }
  }
}

Usage:

<a my-link="l" ng-bind="l.name"></a>

http://plnkr.co/edit/p8PsWosSPmGlTjrjSN9S?p=preview

If it fits your needs you could also go with ngHref as Chandermani noted. It doesn't add href if its undefined.

<a ng-href="{{l.url}}" ng-bind="l.name"></a>
hansmaad
  • 18,417
  • 9
  • 53
  • 94
0

You usually use a multiple elements with combination of ng-if with the inclusion/exclusion of the attributes on the corresponding element. For e.g consider a table row which has to show a link like Edit and suppose its attribute is meant to be added on say some boolean field foo.

<tr ng-repeat="item in items">
<td>
<a href="#/edit?id=foo" ng-if="item.foo" custom-attr="foo">Edit</a>
<a href="#/edit?id=foo" ng-if="!item.foo">Edit</a>
</td>
<!--other columns -->
</tr>

Plunk: http://plnkr.co/edit/G4aTyxQdbeJdWwtmu91t?p=preview

deostroll
  • 11,661
  • 21
  • 90
  • 161