Search code examples
htmlangularjshighlighting

AngularJs - html rendering


We use elastic search highlighter and get the below code from the highlighter.

<span style='font-weight:bold;color:red;'>Baskar</span> Test

We display the result in html as follows.

                     <tr
                        ng-repeat="result in searchModelResult">                        
                        <td><p ng-bind-html="result.name"></p></td>                     
                    </tr>

I have included sanitize.js and have ngSanitize in the angular module. Still i dont see the html effect like red color font and bold font.

Am i missing anything here?

Thanks, Baskar.S


Solution

  • You need to do 2 things, first remove

    {{result.name}}
    

    as Daniel said... then you need to say to angular to trust in that html in your controller:

    myApp.controller('MyCtrl', function ($scope, $sce) {
        $scope.result.name = $sce.trustAsHtml('<span style="font-weight:bold; color:red;">Baskar</span> Test');
    });
    

    You can see the full documentation of $sce here

    If you need to iterate inside a ng-repeat you can create a filter:

    myApp.filter('unsafe', function($sce) { return $sce.trustAsHtml; });
    

    And then use it in the view:

    <tr ng-repeat="result in searchModelResult">                        
        <td><p ng-bind-html="result.name | unsafe"></p></td>                     
    </tr>