14

如何在AngularJS中有条件地用标签包围文本?例如:

function Controller($scope){
  $scope.showLink = true or false, retrieved from server;
  $scope.text = "hello";
  $scope.link = "..."
}

如果 {{showLink}} 为假

<div>hello</div>

别的

<div><a href="{{link}}">hello</a></div>
4

5 回答 5

15

ngSwitch适用于:

<div ng-switch="!!link">
    <a ng-href="{{link}}" ng-switch-when="true">linked</a>
    <span ng-switch-when="false">notlinked</span>
</div>
于 2013-05-16T05:37:34.587 回答
11

据我所知,没有开箱即用的功能可以做到这一点。我对其他答案并不满意,因为它们仍然要求您在视图中重复内部内容。

好吧,你可以用你自己的指令来解决这个问题。

app.directive('myWrapIf', [
  function()
    {
      return {
        restrict: 'A',
        transclude: false,
        compile:
          {
            pre: function(scope, el, attrs)
              {
                if (!attrs.wrapIf())
                  {
                    el.replaceWith(el.html());
                  }
              }
          }
      }
    }
]);

用法:

<a href="/" data-my-wrap-if="list.indexOf(currentItem) %2 === 0">Some text</a>

仅当满足条件时,“某些文本”才会成为链接。

于 2014-12-19T15:54:49.927 回答
3

尝试

<div ng-show="!link">hello</div>
<div ng-show="!!link"><a href="{{link}}">hello</a></div>
于 2013-05-16T05:34:17.560 回答
2

您可以使用该ng-switch指令。

<div ng-switch on="showLink">
    <div ng-switch when="true">
        <a ng-href="link">hello</a>
    </div>
    <div ng-switch when="false">
        Hello
    </div>
</div>
于 2013-05-16T05:34:37.513 回答
1

修改后的 Casey 回答以支持 AngularJS 表达式:

app.directive('removeTagIf', ['$interpolate', function($interpolate) {
  return {
    restrict: 'A',
    link: function(scope, el, attrs) {
      if (scope.$eval(attrs.removeTagIf))
        el.replaceWith($interpolate(el.html())(scope));
    }
  };
}]);

用法:

<a href="/" remove-tag-if="$last">{{user}}'s articles</a>
于 2016-09-14T17:22:27.647 回答