最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to surround text with tag conditionally in AngularJS? - Stack Overflow

programmeradmin0浏览0评论

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

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

if {{showLink}} is false

<div>hello</div>

else

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

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

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

if {{showLink}} is false

<div>hello</div>

else

<div><a href="{{link}}">hello</a></div>
Share Improve this question asked May 16, 2013 at 5:30 aztackaztack 4,5947 gold badges35 silver badges57 bronze badges
Add a comment  | 

5 Answers 5

Reset to default 15

ngSwitch is suitable for that:

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

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.

Try

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

You can use the ng-switch directive.

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

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

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>
发布评论

评论列表(0)

  1. 暂无评论