Tuesday, February 17, 2015

ng-bind-html

The ng-bind-html directive is used in places where we need to parse HTML content and render the output instead of just displaying the HTML tags in the view, by default any value bound to this directive will be passed through $sanitize to validate and clean so that no unsafe inputs are rendered to the view, this validation process might filter out some of the HTML tags from the source which are deemed to be un-safe. The $sce can be used to skip the validation process and render the content as it is in the view. $sce.trustAsHtml instructs Angular that the content is valid and can skip the validation done by $sanitize, this makes sure that the full HTML is parsed and rendered as output in the View.

The following example uses $sce.trustAsHtml to display HTML content to the view using ng-bind-html directive.


<html ng-app>
  <head>
    <meta charset="utf-8">
    <title>AngularJS - $sce Basic</title>
    <script src="angular.min.js"></script>
    <script>
      function sceController($scope, $sce){
       $scope.HTMLContent = "<b>Render me as HTML</b>";
       $scope.TrustedHTMLContent = $sce.trustAsHtml("<b>Render me as HTML</b>");
      }
    </script>
  </head>
  <body>
<div ng-controller="sceController">
<u>HTML Content</u>:
<div ng-bind-html="HTMLContent"></div><br/>
<u>Trusted HTML Content</u>:
<div ng-bind-html="TrustedHTMLContent"></div><br/>
</div>
  </body>
</html> 

Output

Notice that the output from the $scope variableHTMLContent” is not rendered to the view, this is because $scope.HTMLContent is not marked as safe using $sce.trustAsHtml, the same content in $scope.TrustedHTMLContent  when passed through $sce.trustAsHtml is rendered in the view. 

Search Flipkart Products:
Flipkart.com

No comments: