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?
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
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With