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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16579597/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 05:12:15  来源:igfitidea点击:

How to surround text with tag conditionally in AngularJS?

javascriptangularjsangularjs-directive

提问by aztack

How to surround text with tag conditionally in AngularJS? for example:

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

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

if {{showLink}} is false

如果 {{showLink}} 为假

<div>hello</div>

else

别的

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

回答by Umur Kontac?

ngSwitchis suitable for that:

ngSwitch适用于:

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

回答by Casey

As far as I can tell there's no out-of-the-box feature to do this. I wasn't really satisfied with the other answers because they still require you to repeat the inner contents in your view.

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

Well, you can fix this with your own directive.

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

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

Usage:

用法:

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

"Some text" will be a link only if the condition is met.

“某些文本”只有在满足条件时才会成为链接。

回答by Arun P Johny

Try

尝试

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

回答by NilsH

You can use the ng-switchdirective.

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

回答by Qualtagh

Modified version of Casey's answer to support AngularJS expressions:

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));
    }
  };
}]);

Usage:

用法:

<a href="/" remove-tag-if="$last">{{user}}'s articles</a>