I have a person with a name and an optional home page. How do I optionally wrap their name in an anchor tag?
<ul ng-repeat='person in people'>
<li>
<a href="{{person.website}}">
{{person.name}}
</a>
</li>
</ul>
or in the case where person.website
is nil
<ul ng-repeat='person in people'>
<li>
{{person.name}}
</li>
</ul>
In rails I would use the method <%= link_to_unless person.website.blank?, seller.name, seller.website %>
How do I do this in AngularJS?
You could add the following function to your scope:
$scope.linkToUnless = function(condition, label, href) {
return condition ? '<a href="'+href'+">'+label+'</a>' : label;
};
or you could rework your HTML to something like:
<ul ng-repeat='person in people'>
<li>
<a href="{{person.website}}" ng-if="person.website">
{{person.name}}
</a>
<span ng-if="!person.website">
{{person.name}}
</span>
</li>
</ul>
(just a note inspired by OP's comment, ng-if
is available only since anugular 1.1.5; for older versions use ng-show
and ng-hide
instead
or you could write a custom directive and use it like:
<link-to-if href="person.website" label="person.name" />
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