ng-bind-html to prevent executing scripts in content

855 views Asked by At

The problem I'm facing is I'm getting data from server which has HTML contents

<p> hello <a class='mention'data-id='1'>Amerr</a></p>

Since ng-bind-html Santaize and it will remove all the potential threats and also attributes like data-id='1'. Which I need for my directives. So I use

  1. $compile for my directive to act on the anchor tag .
  2. $sce.trustAsHtml to return the comipled code.

so if there is any text like

"<p> {{axy}} /p>\n"

$compile(html_code)($scope)

This will execute code and causes angular to execute expression causing problem. Help me how to solve this problem.

var controller= app.controller('Homecontrol', function($scope) {

  $scope.body = socket.emit('hello');
  $scope.to_trusted = function(html_code) {
    if (/<[a-z][\s\S]*>/i.test(html_code)) {
      var a = $compile(html_code)($scope);
      return $sce.trustAsHtml(a[0].innerHTML);
    } else {
      return html_code;
    }
  }

});

app.directive('mention', function (){
  return {
    restrict: 'AEC',
    transclude: true,
    template: '<a ng-transclude ></a>',
    replace: true,
   }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<p ng-bind-html=toTrust(body) ></p>

1

There are 1 answers

0
Amerrnath On BEST ANSWER

I finally did by parsing the string by . Jquery.parseHTML and compiled the required DOM with which needs to $compile for directive to act on it. and replaced by the DOM.