0

Following ajax request returns HTML data which is then placed in

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

Ajax request is as follows:

    $http.post(url, data, config)
      .success(function (data, status, headers, config) {
         $scope.result_data = data;
      })

Returned HTML is :

<a href='#' ng-click="exe('test123')">test123</a>

But when it is rendered in result, no ng-click attribute is available when element is inspected. How to get these parameters rendered as they are in ajax response? Am I missing anything?
Any help is much appreciated.

meen
  • 2,287
  • 3
  • 23
  • 42

2 Answers2

1

The HTML you are returning is sanitized using $sanitize service.

For your code to work as you expect it you need to explicitly tell that it's a trusted html.

$http.post(url, data, config)
  .success(function (data, status, headers, config) {
      $scope.result_data = $sce.trustAsHtml(data);
  });

However, as you can see from this plunker the function does not work. As Zamrony pointed out, you will need to compile the returned HTML (Angular does not see it).

You can use this directive to do this efficiently: https://github.com/incuna/angular-bind-html-compile

It was used in this answer.

Community
  • 1
  • 1
Deividas
  • 6,437
  • 2
  • 26
  • 27
1

Your html contains ng-click directive which need to be compiled first. ng-bind-html directive does not automatically do this I believe.

You may need to change it to something like this

<p your-own-compile="result_data"></p>

And create new directive to handle compilation.

yourAngularModule.directive('yourOwnCompile', ['$compile', function ($compile) {
     var linker = function(scope, element, attr) {
         element.append($compile(attr.yourOwnCompile)(scope));
     }

     return {
        restrict : 'A',
        link : linker           
     }
}]);

Better solution is to just deliver JSON data without any html markup.

Zamrony P. Juhara
  • 5,222
  • 2
  • 24
  • 40
  • Thanks @Zamrony, Could you please provide a link for documentation? I am new to angularjs, so I want to read it in detail about this. – meen Oct 19 '16 at 10:13