AngularJs Return HTML from Controller

ANEDev picture ANEDev · Oct 22, 2015 · Viewed 8.5k times · Source

I try to return some HTML code from my AngularJs controller to the html data.

This is path of my html :

<div align="right">
   {{chooseHtmlElement()}}">
</div>

And this is path of my AngularJs Controller:

   $scope.chooseHtmlElement= function () {
        var sum = $scope.chiQuadSum();
        if (isNaN(sum)) {
            return "";
        }
        if (sum > 17.00) {
            return "<i class=\"fa fa-minus-circle\" style=\"color:red;\"></i>";
        } else if (sum < 14.00) {
            return "<i class=\"fa fa-check-circle\" style=\"color:green;\"></i>";
        } else {
            return "<i class=\"fa fa-circle\" style=\"color:orange;\"></i>";
        }
    }

The problem is when I return these string, the element is not shown as html element, but as text which you can read. Is there any possibility returning these string as html element?

Answer

Pankaj Parkar picture Pankaj Parkar · Oct 22, 2015

While binding html on view in angular js you need to use ng-bind-html directive. But before binding html, you need to sanitize that html by using $sce.trustAsHtml method of ngSanitize module.

<div align="right" ng-bind-html="chooseHtmlElement() | trustedhtml"></div>

Filter

app.filter('trustedhtml', 
   function($sce) { 
      return $sce.trustAsHtml; 
   }
);