AngularJS data bind in ng-bind-html?
Asked Answered
R

3

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..

Rein answered 27/12, 2013 at 6:41 Comment(2)
may be you want transclude? docs.angularjs.org/api/ng.directive:ngTranscludeLeyte
Look this post is similar with your caseCordelier
K
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>
Kibitka answered 21/8, 2014 at 7:8 Comment(1)
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 gives a great explanation of $compile vs. $interpolate vs. $parse.Madalena
A
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>
Aeolus answered 27/12, 2013 at 7:54 Comment(0)
D
-3

What about?

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

Danielldaniella answered 27/12, 2013 at 7:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.