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



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

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

如果{{showLink}}是false

<div>hello</div>
其他

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

ngSwitch适合:

<div ng-switch="!!link">
    <a ng-href="{{link}}" ng-switch-when="true">linked</a>
    <span ng-switch-when="false">notlinked</span>
</div>

据我所知,没有现成的功能可以做到这一点。我对其他答案不是很满意,因为它们仍然要求你在视图中重复内部内容。

好吧,你可以用你自己的指令修复这个问题。

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>

Try

<div ng-show="!link">hello</div>
<div ng-show="!!link"><a href="{{link}}">hello</a></div>

您可以使用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>

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>

最新更新