I have a initial value of
$scope.abc = 'abc'
and perhaps under a click event I want to convert the value to
$scope.abc = '<h1>abc</h1>'
I know there are things like ng-bind to escape html, but is there any more quick way to do it?
I have a initial value of
$scope.abc = 'abc'
and perhaps under a click event I want to convert the value to
$scope.abc = '<h1>abc</h1>'
I know there are things like ng-bind to escape html, but is there any more quick way to do it?
No, there isn't a quick way to escape HTML. In fact, a lot of the difficulty you're seeing is deliberate and safety-minded, as the ability to include arbitrary user-provided HTML is a vector that allows for cross-site scripting, malicious full-page takeovers, and a host of other troubles. Angular combats this by making it really easy to safely insert arbitrary text, and really hard to insert arbitrary markup. (Of course, the HTML you're describing may be hard-coded in your script, but Angular doesn't treat that necessarily any differently.)
I'd also disagree that changing the markup is the right way to go anyway: <h1>
has a very different semantic meaning than an arbitrary <p>
, <div>
, or <span>
, so if you want to adjust the way that string is displayed within your page, you should probably do so with ng-class
or ng-if
.
// JS
$scope.callOutAbc = true;
// CSS
.called-out { font-size: 36pt; font-weight: bold; /* ... */ }
// HTML
<header ng-class="{ 'called-out': callOutAbc }">{{ abc }}</header>
or
<div ng-if="!callOutAbc">{{ abc }}</div>
<h1 ng-if="callOutAbc">{{ abc }}</h1>
abc
`. Unfortunately it doesn't look like there's a simple way to do that out-of-the box. This was the most helpful resource I found: https://stackoverflow.com/questions/9381926/angularjs-insert-html-into-view – RobertAKARobin Oct 17 '16 at 22:13