Development Shack Technology Understood

Angularjs ngBindHtml & $sce.trustAsHtml()  

Imagine this simple controller:

mainApp.controller('PageController', function ($scope, $http, $sce) {

    $scope.posts = [];

    $http.get('/api/posts').then(function (resp) {
        if (resp.status == 200) {
            $scope.posts = resp.data;
        }
    });

});

Along with this HTML:

<div class="container">
    <article itemscope itemtype="http://schema.org/Article" ng-repeat="article in posts">
        <header>
            <h2>{{ article.title }}</h2>
            <time itemprop="datePublished" content="{{ article.date }}" class="date">{{ article.date }}</time>
        </header>
        <div itemprop="articleBody">
            <div ng-bind-html="article.excerpt"></div>
        </div>
    </article>
</div>

This will throw an $sce "unsafe" error message. The reason is that pesky ng-bind-html attribute.

People will point you to the $sce.trustAsHtml() function, but it is important to know how to actually use this function!

Merely calling this function will not do the trick. Check out the code below. For each post, I am replacing the property with what $sce.trustAsHtml() is returning.

mainApp.controller('PageController', function ($scope, $http, $sce) {

    $scope.posts = [];

    $http.get('/api/posts').then(function (resp) {
        if (resp.status == 200) {
            for (var i = 0; i < resp.data.length; i++) {
                resp.data[i].excerpt = $sce.trustAsHtml(resp.data[i].excerpt);
            }

            $scope.posts = resp.data;
        }
    });

});

Now everything should function properly.