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

azt*_*ack 14 javascript angularjs angularjs-directive

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

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

如果{{showLink}}为false

<div>hello</div>
Run Code Online (Sandbox Code Playgroud)

其他

<div><a href="{{link}}">hello</a></div>
Run Code Online (Sandbox Code Playgroud)

Umu*_*acı 15

ngSwitch 适合那个:

<div ng-switch="!!link">
    <a ng-href="{{link}}" ng-switch-when="true">linked</a>
    <span ng-switch-when="false">notlinked</span>
</div>
Run Code Online (Sandbox Code Playgroud)


Cas*_*sey 11

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

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

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

用法:

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

只有满足条件时,"某些文本"才会成为链接.