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

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" />
链接地址: http://www.djcxy.com/p/74472.html

上一篇: 附加鼠标滚轮事件监听器不重置滚动惯量

下一篇: 在AngularJS中,我如何可选地将项目包装在链接中