以角度观察对象和信任html的数组

时间:2016-08-22 10:48:41

标签: javascript html angularjs

我有一个控制器可以将项目添加到列表中并使用以下内容信任内容:

app.controller('main', function($scope, $sce, sharedService) {
  this.sharedService = =sharedService;
  this.sharedService.items = [];
  this.newItem = () => {
    this.sharedService.items.push({
      html: ''
    });
  };
  $scope.$watch(() => this.sharedService.items, function(newValue, oldValue) {
    newValue.forEach(function(item) {
        item.html = $sce.trustAsHtml(item.html);
    });
  }, true);
});

但我在其他视图中收到错误Attempted to trust a non-string value in a content requiring a string: Context: html我使用ng-bind-html显示项目列表并显示html,但为什么我收到此错误以及如何修复它?

1 个答案:

答案 0 :(得分:1)

我收到此错误是因为当我更改$watch时再次触发item.html。为了解决这个问题,我添加了检查item.html是否已经 信任

if (item.html && !item.html.$$unwrapTrustedValue) {
    item.value = $sce.trustAsHtml(item.value);
}