在我的AngularJS控制器中,我具有以下作用域函数:
$scope.show_description = function () {
return ($scope.details.description.length) ? $sce.trustAsHtml(newlinesFilter($scope.details.description)) : 'edit to enter a description';
};
$ scope.details.description的值最初包含带有结尾行的文本,newlinesFilter用BR替换。
app.filter('newlines', [function () {
return function(text){
return text.replace(/\n/g, '<br/>');
}
}]);
在我的HTML中:
<span ng-bind-html="show_description()"></span>
一切似乎都能正常工作,但是我在控制台中收到此跟踪错误:
Error: [$sce:unsafe] http://errors.angularjs.org/1.2.16/$sce/unsafe
at Error (native)
at http://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js:6:450
at e (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js:114:160)
at getTrusted (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js:115:443)
at Object.e.(anonymous function) [as getTrustedHtml] (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js:117:175)
at Object.fn (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js:188:375)
at h.$digest (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js:106:311)
at h.$apply (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js:109:287)
at http://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js:18:23
at Object.d [as invoke] (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js:34:265) angular.js:9778
最佳答案
在show_description()
函数中,您希望通过$sce.trustAsHtml()
运行所有返回值,而不仅仅是非默认值。因此,像这样修改return语句:
return $sce.trustAsHtml(($scope.details.description.length) ? $filter('newlines')($scope.details.description) : 'edit to enter a description');
Plunker
关于javascript - 使用ng-bind-html和$ sce.trustAsHtml()获取JS错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24049213/