Mastering Web Application

(Rick Simeone) #1

Displaying and Formatting Data


Using the ng-bind-html-unsafe directive we will get the HTML fragment with the
tags interpreted by a browser.


Extreme care should be taken when using the ng-bind-html-unsafe directive. Its
usage should be limited to cases where you fully trust or can control the expression
being evaluated. Otherwise malicious users might inject any arbitrary HTML on
your page.


AngularJS has one more directive that will selectively sanitize certain HTML tags
while allowing others to be interpreted by a browser: ng-bind-html. Its usage is
similar to the unsafe equivalent:


<p ng-bind-html="msg"></p>

In terms of escaping the ng-bind-html directive is a compromise between behavior
of the ng-bind-html-unsafe (allow all HTML tags) and the interpolation
directive (allow no HTML tags at all). It might be a good alternative for cases where
we want to allow some HTML tags entered by users.


The ng-bind-html directive resides in a separate module
(ngSanitize) and requires inclusion of an additional source
file: angular-sanitize.js.

Don't forget to declare dependency on the ngSanitize module if you plan to use the
ng-bind-html directive:


angular.module('expressionsEscaping', ['ngSanitize'])
.controller('ExpressionsEscapingCtrl', function ($scope) {
$scope.msg = 'Hello, <b>World</b>!';
});

Unless you are working with existing legacy systems (CMS,
back-ends sending HTML, and so on.), markup in the model
should be avoided. Such markup can't contain AngularJS
directives and requires the ng-bind-html-unsafe or ng-
bind-html directive to obtain desired results.

Conditional display


Showing and hiding parts of the DOM based on some conditions is a common
requirement. AngularJS comes equipped with four different sets of directives for this
occasion (ng-show/ng-hide, ng-switch-*, ng-if and ng-include).

Free download pdf