Saidh
Saidh

Reputation: 1141

AngularJS data bind in ng-bind-html?

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

Upvotes: 19

Views: 17530

Answers (3)

Jennie Ji
Jennie Ji

Reputation: 809

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>

Upvotes: 21

Stewie
Stewie

Reputation: 60396

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>

Upvotes: 7

Miraage
Miraage

Reputation: 3464

What about?

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

Upvotes: -3

Related Questions