Mastering Web Application

(Rick Simeone) #1
Chapter 4

Filters and DOM manipulation

At times it might be tempting to return HTML markup as a result of filter's
execution. In fact AngularJS contains one filter that does exactly that: linky
(in the separate ngSanitize module).


It turns out, in practice, that filters outputting HTML are not the best idea.
The main problem is that to render output of such a filter we need to use one
of the binding directives described earlier on ngBindUnsafeHtml or ngBindHtml.
Not only does it make the binding syntax more verbose (as compared to simply
using {{expression}}) but potentially makes a web page vulnerable to HTML
injection attacks.


To see some issues involving filters outputting HTML we can examine a simple
highlight filter:


angular.module('highlight', [])

.filter('highlight', function(){

return function(input, search) {
if (search) {
return input.replace(new RegExp(search, 'gi'),
'<strong>$&</strong>');
} else {
return input;
}
};
});

You can immediately see that this filter contains hardcoded HTML markup.
As a result we can't use it with the interpolation directive but need to write a
template like:


<input ng-model="search">
<span ng-bind-html="phrase | highlight:search"></span>

On top of this the HTML markup outputted from a filter can't contain any
AngularJS directives as those wouldn't be evaluated.


A custom directive will, most of the time, solve the same problem in a more
elegant way, without introducing potential security hazards. Directives are covered
in Chapter 9, Building Advanced Directives and Chapter 10, Building AngularJS Web
Applications for an International Audience.

Free download pdf