使用ng-bind-html和$ sce.trustAsHtml()获取JS错误

时间:2014-06-04 23:23:00

标签: javascript angularjs

在我的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

1 个答案:

答案 0 :(得分:1)

show_description()函数中,您希望通过$sce.trustAsHtml()运行所有返回值,而不仅仅是非默认值。所以修改return语句如下:

return $sce.trustAsHtml(($scope.details.description.length) ? $filter('newlines')($scope.details.description) : 'edit to enter a description');

Plunker