javascript - 以 Angular 观察对象数组并信任 html

标签 javascript html angularjs

我有一个 Controller ,可以将项目添加到列表中并使用以下方式信任内容:

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);
});

但我收到错误 尝试信任需要字符串的内容中的非字符串值:上下文:html 在其他 View 中我正在使用 ng-bind-html 和显示项目列表它显示 html,但为什么我收到此错误以及如何修复它?

最佳答案

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

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

关于javascript - 以 Angular 观察对象数组并信任 html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39077594/

相关文章:

javascript - 相对位置父级内垂直居中的绝对位置 div - 在 Chrome 中工作,但在 Safari 等中以主体为中心?

javascript - 如何提高集会看板栏中显示的 100 张卡片的限制?

javascript - 如何在单击矩形时在 html Canvas 中的矩形框中获取下拉警报?

html - 在@media 中隐藏包含带有 css 的 URL 的 div

javascript - 如何在angular js中获取窗口高度

javascript - Javascript 的增量机会增加?

javascript - 选项.删除();不起作用,奇怪的行为

javascript - 单击 Bootstrap 分页链接调用 jquery 函数

javascript - Node/Express Js如何从 Angular 获取ajax参数

javascript - 为信用卡禁用 Safari 自动填充