Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to conditionally add attributes to an element using Angular? (Not only attribute data, the whole attribute)

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?

like image 776
THpubs Avatar asked Dec 24 '22 17:12

THpubs


2 Answers

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

like image 51
mido Avatar answered Jan 05 '23 01:01

mido


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>
like image 27
hansmaad Avatar answered Jan 05 '23 00:01

hansmaad