Angular过滤器返回HTML

16

我想在angularjs 1.2中使用unsafe-html。虽然不带html的过滤器可以工作,但是带html的却不能。我的做法:

我在html头部添加了angular-sanitize:

<script src="~/Scripts/angular.js"></script>
<script src="~/Scripts/angular-sanitize.js"></script>

我的Angular模块:

var myApp = angular.module('myApp', ['ngSanitize'])
    .filter('convertState', function ($sce) {
        return function (state) {
            if (state == 1) {
                return $sce.trustAsHtml("<strong>" + state + "</strong> special state");
            }
            else {
                return $sce.trustAsHtml("<strong>"+state + "</strong> normal state");
            }
        }
    });

我的Html:

<td><span ng-bind-html="f.state | convertstate"></span></td>

编辑:将ng-bind-html-unsafe更新为ng-bind-html

2个回答

23

@zoidbergi,您能否指出这里的问题:http://plnkr.co/edit/0bHeXrarRP7IAciqAYgM?p=preview 它似乎可以工作。 - musically_ut
原来是大小写敏感的拼写错误!不过你的回答解决了我另一个问题。谢谢! - daniel
当使用ngSanitize时,并不总是需要使用$sce.trustAsXXX()(实际上在这种情况下并不需要)。这就是净化的全部目的。 - gkalpak

3
你可以使用类似以下的内容:
app.directive('toHtml', function() {
  return {
    restrict: 'A',
    link: function (scope, el, attrs) {
      el.html(scope.$eval(attrs.toHtml));
    }
  };
});

用法如下:

<p to-html="name | convertState"></p>

http://plnkr.co/edit/Av2rmeXp7phkDdbYUbxF


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接