【问题标题】:AngularJS data bind in ng-bind-html?ng-bind-html中的AngularJS数据绑定?
【发布时间】:2014-01-14 18:35:28
【问题描述】:

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

我有一个

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

我的角度模板看起来像,

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

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

所以,我想在{{caption}}中绑定数据。

提前谢谢..

【问题讨论】:

标签: angularjs ng-bind-html


【解决方案1】:

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

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

然后像这样写HTML:

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

【讨论】:

  • 赞成建议 $interpolate 而不是 $compile$interpolate 返回一个字符串,这是 $scope.html 在这种情况下需要的; $compile 返回一个 DOM 元素。 This answer 很好地解释了 $compile$interpolate$parse
【解决方案2】:

您需要编译您的 HTML sn-p,但建议在指令中执行此操作。

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

【讨论】:

    【解决方案3】:

    怎么样?

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-31
      • 1970-01-01
      • 2016-01-21
      • 1970-01-01
      • 1970-01-01
      • 2013-09-26
      • 2014-01-13
      • 1970-01-01
      相关资源
      最近更新 更多