Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 666
aztack Avatar asked May 16 '13 05:05

aztack


5 Answers

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>
like image 96
Umur Kontacı Avatar answered Oct 17 '22 06:10

Umur Kontacı


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.

like image 22
Casey Avatar answered Oct 17 '22 06:10

Casey


Try

<div ng-show="!link">hello</div>
<div ng-show="!!link"><a href="{{link}}">hello</a></div>
like image 45
Arun P Johny Avatar answered Oct 17 '22 04:10

Arun P Johny


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>
like image 24
NilsH Avatar answered Oct 17 '22 05:10

NilsH


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>
like image 28
Qualtagh Avatar answered Oct 17 '22 06:10

Qualtagh