Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 772
Derek 朕會功夫 Avatar asked Dec 15 '14 21:12

Derek 朕會功夫


1 Answers

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.

like image 103
Florian F. Avatar answered Nov 07 '22 10:11

Florian F.