AngularJS数据绑定在ng-bind-html中?

Sai*_*idh 19 angularjs ng-bind-html

是否可以将范围变量的数据绑定到即将绑定为ng-bind-html的html?

即,我有一个

html ="<div>{{caption}}</div>";
Run Code Online (Sandbox Code Playgroud)

和我的角模板看起来像,

<div ng-bind-html="html"></div>
Run Code Online (Sandbox Code Playgroud)

范围变量的值caption在角度控制器中设置.

所以,我想绑定数据{{caption}}.

提前致谢..

Jen*_* Ji 21

你应该使用$ interpolate而不是$ compile.
像这样写控制器:

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

然后像这样写HTML:

<div ng-controller="MyCtrl">
    <div ng-bind-html="html"></div>
</div>
Run Code Online (Sandbox Code Playgroud)


Ste*_*wie 7

您需要编译HTML代码段,但建议在指令中执行此操作.

app.controller('MyCtrl', function($compile){
  $scope.caption = 'My Caption';
  $scope.html = $compile('<div>{{caption}}</div>')($scope);
});
Run Code Online (Sandbox Code Playgroud)
<div ng-bind-html="html"></div>
Run Code Online (Sandbox Code Playgroud)


Mir*_*age -3

关于什么?

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