8

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?

7
  • 1
    Why not using ngClass ? Or ngBindHtml ? Commented Dec 15, 2014 at 21:05
  • @FlorianF. - Since I'm directly doing some calculation on the spot (and it's inside two ng repeat), I can't use ng bind html. Commented Dec 15, 2014 at 21:06
  • Yes you can, just call a function instead of an inline if ? It's probably not the best approach though and I would probably go with ngClass or a directive. Commented Dec 15, 2014 at 21:08
  • @FlorianF. It seems you were right, I can indeed use ng-bind-html and put the whole thing inside it. Other doing this, is there no way to create a tag with the {{}} syntax? Commented Dec 15, 2014 at 21:15
  • does {{{ instead of {{ not escape the html? (i know that's how mustache et al work...) Commented Dec 15, 2014 at 21:40

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I agree, controllers should not manipulate DOM, but what about ABC and <strong>all its history</strong> will be deleted? There should be some way semantically to talk about rich text. Lol, maybe a Markdown filter.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.