0

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

Sanjeev Singh
  • 3,976
  • 3
  • 33
  • 38
user1578872
  • 7,808
  • 29
  • 108
  • 206

2 Answers2

1

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>
Facundo Pedrazzini
  • 1,486
  • 14
  • 22
  • Hi, I am getting a list and iterating using ng-repeat in the html. Should I iterate the list in the controller and add $sce.trustAsHtml for each element? – user1578872 May 07 '15 at 19:38
  • not necessarily, you can create a filter as Chris said in this link: http://stackoverflow.com/questions/18340872/how-do-you-use-sce-trustashtmlstring-to-replicate-ng-bind-html-unsafe-in-angu see the second answer (the one witch has 306 points). Tell me if you need an example. – Facundo Pedrazzini May 07 '15 at 19:43
  • @user1578872 I put an example on the answer. – Facundo Pedrazzini May 07 '15 at 19:50
0

You need to remove the second binding expression:

{{result.name}}

It looks like that is overriding the binding from ng-bind-html, and the default binding will HTML escape the string.

Daniel Schaffer
  • 56,753
  • 31
  • 116
  • 165
  • I tried this. Now, i dont see the html tags. But i dont see the html effect. Text color is still in normal color not in red and not in bold. – user1578872 May 07 '15 at 17:17