8

我有一个人的名字和一个可选的主页。我如何选择将他们的名字包装在锚标签中?

<ul ng-repeat='person in people'>
  <li>
    <a href="{{person.website}}">
      {{person.name}}
    </a>
  </li>
</ul>

person.website或者在nil的情况下

<ul ng-repeat='person in people'>
  <li>
    {{person.name}}
  </li>
</ul>

在rails中我会使用该方法<%= link_to_unless person.website.blank?, seller.name, seller.website %>

我如何在 AngularJS 中做到这一点?

4

1 回答 1

5

您可以将以下功能添加到您的范围:

$scope.linkToUnless = function(condition, label, href) {
    return condition ? '<a href="'+href'+">'+label+'</a>' : label;
};

或者您可以将您的 HTML 修改为:

<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>

(只是受 OP 评论启发的注释,ng-if仅在 anugular 1.1.5 之后才可用;对于旧版本ng-show,请ng-hide改用

或者您可以编写一个自定义指令并像这样使用它:

<link-to-if href="person.website" label="person.name" />
于 2013-09-27T21:13:50.420 回答