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?

3
  • 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. Commented Jul 6, 2015 at 5:54
  • 1
    possible duplicate of What is the best way to conditionally apply attributes in Angular? Commented Jul 6, 2015 at 5:58
  • @mido22 Nope.. In there it shows how to add the attribute value conditionally. What I want is to add the whole attribute conditionally Commented Jul 6, 2015 at 9:40

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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>

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.