angularjsng-bind-html

HTML string not binded with angular


<!DOCTYPE html
<body>

<div ng-app="myApp" ng-controller="myCtrl">

<p ng-bind-html="myText"></p>

</div>

<script>
var app = angular.module("myApp", ['ngSanitize']);
app.controller("myCtrl", function($scope) {
    $scope.myText = "<input type='text' value='here'>";
});
</script>

<p><b>Note:</b> This example includes the "angular-sanitize.js",
which has functions for removing potentially dangerous tokens from the HTML.</p>

</body>
</html>

I'm new to angular as well. I could not bind the html text to the angular view. Any suggestions could help.


Solution

  • You shoud use $sce.trustAsHtml() like this

    $scope.myText=$sce.trustAsHtml("<input type='text' value='here'>")
    

    Like this fiddle

    but then you cannot bind scope variables to your html so best way is writing a directive which can be replace with ng-bind-html-unsafe something like

    .directive('bindUnsafeHtml', ['$compile', function ($compile) {
          return function(scope, element, attrs) {
              scope.$watch(
                function(scope) {
                  // watch the 'bindUnsafeHtml' expression for changes
                  return scope.$eval(attrs.bindUnsafeHtml);
                },
                function(value) {
                  // when the 'bindUnsafeHtml' expression changes
                  // assign it into the current DOM
                  element.html(value);
    
                  // compile the new DOM and link it to the current
                  // scope.
                  // NOTE: we only compile .childNodes so that
                  // we don't get into infinite loop compiling ourselves
                  $compile(element.contents())(scope);
                }
            );
        };
    }])
    

    working fiddle