我有一个 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/