Maria Jane Maria Jane - 11 months ago 60
AngularJS Question

quick way to escape html in $scope variable

I have a initial value of

$ = 'abc'

and perhaps under a click event I want to convert the value to

$ = '<h1>abc</h1>'

I know there are things like ng-bind to escape html, but is there any more quick way to do it?

Answer Source

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; /* ... */ }

<header ng-class="{ 'called-out': callOutAbc }">{{ abc }}</header>


<div ng-if="callOutAbc">{{ !abc }}</div>
<h1 ng-if="callOutAbc">{{ abc }}</h1>