19

Is it possible to bind data of scope variable to a html that is about to bind as ng-bind-html?

ie, I have a

html ="<div>{{caption}}</div>";

and my angular template look like,

<div ng-bind-html="html"></div>

the value of scope variable caption is set in angular controller.

So, I want to bind data in {{caption}}.

Thanks in advance..

Jayantha Lal Sirisena
  • 21,216
  • 11
  • 71
  • 92
Saidh
  • 1,131
  • 1
  • 12
  • 21
  • may be you want transclude? http://docs.angularjs.org/api/ng.directive:ngTransclude – KoIIIeY Dec 27 '13 at 06:52
  • Look this [post](http://stackoverflow.com/questions/40024415/using-ng-bind-html-and-sce-trustashtml-create-a-string-with-ng-model-binding/40024560#40024560) is similar with your case – GomuGomuNoRocket Oct 14 '16 at 11:17

3 Answers3

21

You should use $interpolate not $compile. Write the controller like this:

angular.module('app', ['ngSanitize'])
  .controller('MyCtrl', ['$scope', '$interpolate', function($scope, $interpolate){
   $scope.caption = 'My Caption';
   $scope.html = $interpolate('<div>{{caption}}</div>')($scope);
});

Then write the HTML like this:

<div ng-controller="MyCtrl">
    <div ng-bind-html="html"></div>
</div>
James Skemp
  • 8,018
  • 9
  • 64
  • 107
Jennie Ji
  • 769
  • 5
  • 13
  • Upvoted for suggesting `$interpolate` instead of `$compile`. `$interpolate` returns a string, which is what `$scope.html` needs to be in this case; `$compile` returns a DOM element. [This answer](http://stackoverflow.com/a/17901134/4192097) gives a great explanation of `$compile` vs. `$interpolate` vs. `$parse`. – MikeJ Dec 12 '14 at 17:05
7

You need to compile your HTML snippet, but it is recommended to do that inside the directive.

app.controller('MyCtrl', function($compile){
  $scope.caption = 'My Caption';
  $scope.html = $compile('<div>{{caption}}</div>')($scope);
});
<div ng-bind-html="html"></div>
Stewie
  • 60,366
  • 20
  • 146
  • 113
-3

What about?

html = '<div ng-bind="caption"></div>';

Miraage
  • 3,334
  • 3
  • 26
  • 43