AngularJS $sce - sanitize and render content and resources in templates


Example

$sce ("Strict Contextual Escaping") is a built-in angular service that automatically sanitize content and internal sources in templates.

injecting external sources and raw HTML into the template requires manual wrapping of$sce.

In this example we'll create a simple $sce sanitation filter :`.

Demo

.filter('sanitizer', ['$sce', [function($sce) {
     return function(content) {
          return $sce.trustAsResourceUrl(content);
      };
}]);

Usage in template

<div ng-repeat="item in items">
    
    // Sanitize external sources
    <ifrmae ng-src="{{item.youtube_url | sanitizer}}">
    
    // Sanitaize and render HTML 
    <div ng-bind-html="{{item.raw_html_content| sanitizer}}"></div>

</div>