【问题标题】:Display output that contains HTML which is returned from a filter function显示包含从过滤器函数返回的 HTML 的输出
【发布时间】:2014-06-17 13:09:22
【问题描述】:

标记:

<div class="vpScoreInner" ng-bind-html="reason | truncate:limit:20:" ...">

JS:

filter('truncate', function($sce){
            return function(text, overall_limit, line_limit, end){
                if (!text){
                    return;
                }
                var last_blank_index = 0;
                var line_length = 0;
                var overall_length = 0;
                var processed = '';
                var componenets = text.split(' ');
                for (var i = 0; i < componenets.length; i++){
                    c = componenets[i];
                    if (overall_limit && overall_length + c.length >= overall_limit){
                        return $sce.trustAsHtml(processed + end);
                    }

                    if(line_length < line_limit){
                        processed = !!processed ? processed + ' ' + c : c;
                        line_length = line_length + c.length;
                    }
                    else{
                        processed = processed + '<br>'
                        line_length = 0
                    }
                    overall_length = overall_length + c.length;
                }

                return $sce.trustAsHtml(processed);
            }
      });

我实现的这个过滤器既可以根据需要截断文本,也可以将其拆分为不超过 x 个字符的行,而不会在中间截断单词。

问题是普通的 ng-bind
标签被渲染为纯文本,而使用相对较新的 ng-bind-html,文本根本不会被渲染。

【问题讨论】:

标签: angularjs angular-filters


【解决方案1】:

我认为您不需要在这里使用$sce,您的过滤器返回的值直接返回给ngBindHtml 指令,该指令反过来会为您清理和呈现HTML。

如果您查看 $sce.trustAsHTML 的 AngularJS 文档 (https://docs.angularjs.org/api/ng/service/$sce),它会返回一个需要传递给 $sce.getTrustedHTML 的对象

Returns

An object that can be passed to $sce.getTrustedHtml(value) to obtain 
the original value. (privileged directives only accept expressions that 
are either literal constants or are the return value of $sce.trustAs.)

我认为您只需要返回您创建的直接 HTML 字符串,然后让ngBindHTML 完成剩下的工作。

编辑:这是一个简单的过滤器小提琴,它将字符串分成相等的大小并插入双中断:http://jsfiddle.net/mikeeconroy/LfvZf/

【讨论】:

  • 使用 ng-bind-html 是正确的,但也必须将 ngSanitize 添加到模块中。
猜你喜欢
  • 2022-12-31
  • 2018-12-05
  • 1970-01-01
  • 1970-01-01
  • 2015-02-23
  • 1970-01-01
  • 2021-09-25
  • 2015-10-29
  • 2017-09-07
相关资源
最近更新 更多