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
"<b>...
but they both didn't work. Any idea?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With