aztack
aztack

Reputation: 4594

How to surround text with tag conditionally in AngularJS?

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>

Upvotes: 14

Views: 18792

Answers (5)

Qualtagh
Qualtagh

Reputation: 721

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>

Upvotes: 1

Casey
Casey

Reputation: 3353

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.

Upvotes: 11

Umur Kontacı
Umur Kontacı

Reputation: 35478

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>

Upvotes: 15

NilsH
NilsH

Reputation: 13821

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>

Upvotes: 2

Arun P Johny
Arun P Johny

Reputation: 388316

Try

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

Upvotes: 3

Related Questions