【问题标题】:Angular filter return html角度过滤器返回html
【发布时间】:2013-12-15 14:28:49
【问题描述】:

我想在 angularjs 1.2 中使用 unsafe-html。没有 html 的过滤器确实可以工作,而 html 则不能。我的工作:

我在我的 html 头中添加了 angular-sanitize:

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

我的角度模块:

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

【问题讨论】:

    标签: javascript html angularjs


    【解决方案1】:

    ng-bind-html-unsafe 已在 Angular 1.2 中删除。由于您正确地清理了您的输入,您应该只使用ng-bind-html

    示例:http://plnkr.co/edit/0bHeXrarRP7IAciqAYgM?p=preview

    【讨论】:

    • @zoidbergi 你能在这里指出问题吗:plnkr.co/edit/0bHeXrarRP7IAciqAYgM?p=preview 它似乎有效。
    • 原来这是一个区分大小写的错字!不过,您的回答是我遇到的另一个问题。谢谢!
    • 当使用ngSanitize 时,并不总是需要使用$sce.trustAsXXX()(实际上在这种情况下并非如此)。这就是消毒的全部目的。
    【解决方案2】:

    你可以使用类似的东西

    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

    【讨论】:

      猜你喜欢
      • 2017-11-20
      • 2013-08-24
      • 1970-01-01
      • 1970-01-01
      • 2015-05-11
      • 2021-11-22
      • 2020-07-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多