Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In AngularJS, how do I optionally wrap item in a link

Tags:

html

angularjs

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?

like image 960
zhon Avatar asked Sep 27 '13 21:09

zhon


1 Answers

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" />
like image 101
Adam Zielinski Avatar answered Nov 15 '22 05:11

Adam Zielinski