1

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?

Maria Jane
  • 2,353
  • 6
  • 23
  • 39
  • I'm not sure I understand. You want to take a string and just wrap the string in an `h1` tag? That doesn't sound like escaping HTML... – RobertAKARobin Oct 17 '16 at 22:05
  • @RobertAKARobin I mean render it, now I'm seeing the h1 as value when I do {{abc}} in my view. – Maria Jane Oct 17 '16 at 22:06
  • Oh, I see. So you want the `h1` tag to actually show up as an `h1` tag, but instead you're seeing the literal text `

    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
  • not sure what you mean by a faster way of doing this. Use https://docs.angularjs.org/api/ng/directive/ngBindHtml ng-bind-html directive. I assume you were referring in your question to the ng-bind which is just alternate syntax for the {{}} – Mahesh Oct 17 '16 at 22:13

1 Answers1

1

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>
Jeff Bowman
  • 90,959
  • 16
  • 217
  • 251