【问题标题】:AngularJS using $sce.trustAsHtml with ng-repeatAngularJS 使用 $sce.trustAsHtml 和 ng-repeat
【发布时间】:2014-08-18 23:58:17
【问题描述】:

我正在尝试将 $sce.trustAsHtml() 与 ng-repeat 中的对象属性一起使用。结果是 HTML 是完全空白的。 HTML 使用 ngSanitize 正确输出。

<div ng-repeat="question in questions">
    <p ng-bind-html="$sce.trustAsHtml(question.body)">
    </p>
</div>

顺便说一句,我正在使用 AngularJS v1.3.0-beta.3。不确定是否有错误或我做错了什么。

【问题讨论】:

    标签: javascript angularjs angularjs-ng-repeat ng-bind-html ngsanitize


    【解决方案1】:

    或者有一个过滤器:

    angular.module('myApp')
        .filter("sanitize", ['$sce', function($sce) {
            return function(htmlCode){
                return $sce.trustAsHtml(htmlCode);
            }
    }]);
    

    在 html 中:

    <div ng-bind-html="question.body | sanitize"></div>
    

    【讨论】:

    • 它不会为我清理 htmlCode
    【解决方案2】:

    您不能在表达式中使用$sce.trustAsHtml(除非$sce$scope 的属性),因为表达式是在$scope 的上下文中计算的。

    最干净的方法是使用ngSanitize
    第二个最干净的是将$sce.trustAsHtml 公开为$scope 中的函数:

    <div ng-repeat="...">
        <p ng-bind-html="trustAsHtml(question.body)"></p>
    </div>
    
    $scope.trustAsHtml = $sce.trustAsHtml;
    

    【讨论】:

    • 感谢您的解释。在服务中使用 $sce 时遇到问题 - 仅在过滤器和指令中工作
    • 这正是我要找的,它简短、简单、甜美。谢谢!
    • 如何在控制器中使用$sce.trustAsHtml(questions) 并仅使用&lt;p ng-bind-html="question.body"&gt;&lt;/p&gt;。 ?
    • @HardikMishra,这也是可能的(而且比把它放在模板中更好)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-11
    • 2017-12-22
    • 1970-01-01
    • 1970-01-01
    • 2012-10-10
    相关资源
    最近更新 更多