过滤angularjs中的用户输入

时间:2015-04-26 14:51:22

标签: javascript angularjs

我使用ng-repeat

以角度构建了一些东西
            <ul class="messages">
                <li ng-repeat="e in enquiries">
                    <img src="/img/avatar.jpg" alt="">
                    <div>
                        <div>
                            <h5>{{e.user}}</h5>
                            <span class="time"><i class="fa fa-clock-o"></i> {{e.created_at}}</span>
                        </div>
                        <p>{{e.post}}</p>
                        <div ng-if="e.is_replied == 'no'"><a href="/hub/delete">Delete</a></div>
                    </div>
                </li>
            </ul>

这是显示用户的输入。但是我没有htmlentities对用户输入进行编码,而是直接将用户输入插入数据库,例如<a href="jscode">Hack</a>但是我注意到当我使用上面的代码显示此消息时。它仍然会将消息显示为<a href="jscode">Hack</a>,而不是显示&#34; hack&#34;链接。我可以说在这种情况下,角度会自动消毒输入吗?我是否还需要使用&#34; ng-bind-html&#34;?

2 个答案:

答案 0 :(得分:0)

如果您的帖子内容是HTML,则需要更改为ng-bind-html:

<p ng-bind-html="e.post | to_trusted"></p>

此外,您还需要一个过滤器来消毒:

app.filter('to_trusted', ['$sce', function ($sce) {
    return function (text) {
        return $sce.trustAsHtml(text);
    };
}])

答案 1 :(得分:0)

最好的选择是$sanitize服务,它是ngSanitize模块的一部分。使用ng-bind-html指令,该指令自动使用$sanitizeng-bind-html会将您的文字插入原始HTML,但前提是它位于安全HTML的ngSanitize白名单中。如果您完全确定HTML是安全的(例如,如果您在后端清理它),那么无论白名单如何,都可以通过一种方式告诉Angular将其填充。