ng-bind-html剥离元素属性

rxd*_*azn 21 angularjs

我正在尝试插入一个包含模板中的标记的字符串.

在控制器中:
$scope.message = "Hello moto <a ui-sref='home.test'>click</a>";

模板:

<div ng-bind-html="message.text"></div>
Run Code Online (Sandbox Code Playgroud)

其呈现为:

<div ng-bind-html="message.text" <div="" class="ng-binding">Hello moto <a>click</a></div>
Run Code Online (Sandbox Code Playgroud)

试图使用以下过滤器也无济于事; 对于任何一个评论选择,文本都是简单的转义:

angular.module('test-filters', ['ngSanitize'])
    .filter('safe', function($sce) {
            return function(val) {
                return $sce.trustAsHtml(val);
                //return $sce.trustAsUrl(val);
                //return $sce.trustAsResourceUrl(val);
            };
    });
Run Code Online (Sandbox Code Playgroud)

如何插入我的字符串而不转义它或剥离属性?

编辑:Plunker http://plnkr.co/edit/H4O16KgS0mWtpGRvW1Es?p=preview(使用sylwester的版本更新,该版本引用了ngSanitize

syl*_*ter 30

让我们来看看这里http://jsbin.com/faxopipe/1/edit它现在排序.它没有用,因为标签'ui-sref'中有另一个指令,所以你必须使用$ sce服务.

在你的js请添加方法:

 $scope.to_trusted = function(html_code) {
    return $sce.trustAsHtml(html_code);
Run Code Online (Sandbox Code Playgroud)

在视野中:

<p ng-bind-html="to_trusted(message)"></p>
Run Code Online (Sandbox Code Playgroud)

  • 如果我们说trustAsHtml,我们如何防止XSS? (2认同)
  • 实现作为过滤器(而不是范围函数)也可以很好地工作. (2认同)
  • 谢谢你。我们可以让这更简单——`$scope.to_trusted = $sce.trustAsHtml;` (2认同)