Derek 朕會功夫
Derek 朕會功夫

Reputation: 94379

Inline tags in AngularJS

So I'm doing something like this:

{{someFlag ? "<b>Bold Text</b>" : "<i>Italic Text</i>"}}

But as everyone knows, things don't always go that smoothly. When I included a "tag" in the inline code, AngularJS seems to completely ignored the whole thing and rendered the source code.

I tried

"\<b>.....

and

"&lt;b>...

but they both didn't work. Any idea?

Upvotes: 8

Views: 1320

Answers (1)

Florian F.
Florian F.

Reputation: 4700

As posted in the comments, you have a few options, from worse to better imho :

First is to use ngBindHtml

<div ng-bind-html="italicOrBold('With ngBindHtml', someFlag)"></div>

$scope.italicOrBold = function(text, bold){
    return $sce.trustAsHtml(bold ? '<b>Test</b>' : '<i>Test</i>');
}

Second is to use ngClass, which is not a too bad design

<div ng-class="{'text-bold' : someFlag, 'text-italic' : !someFlag}">With ngClass</div>

.text-bold{
  font-weight:bold;
}

.text-italic{
  font-style:italic;
}

And third and better, make a directive

<div bold-me-up="someFlag">Or even better with a directive</div>

.directive('boldMeUp', function(){
  return {
        template: '<div ng-class="{\'text-bold\' : boldMeUp, \'text-italic\' : !boldMeUp}" ng-transclude></div>',
        restrict: 'A',
        replace: true,
        transclude: true,
        scope: {
            boldMeUp: '='
        },
        link: function postLink(scope, element, attrs) {
        }
   };
})

Plunker demo

And to answer your comment, I don't think there's a way to create tag with mustache syntax it's just not the way it has been designed, expressions (the thing between curly braces) are basically calls to controller and controllers shouldn't be used to manipulate DOM.

Upvotes: 5

Related Questions