如何在ng-bind-html中计算angular过滤器来格式化和显示已定义的HTML资源?



我遇到了一个情况,我需要一些见解。我有一个定义的资源,包含一个HTML片段和一个格式占位符(@Resource.Foo)…

<p>Been caught stealing on {0}</p>

我有一个自定义的角格式过滤器(https://gist.github.com/litera/9634958)

在我的。cshtml中,我调用了以下绑定…

{{ '@Resource.foo' | format: ( ctrl.DateProperty | date: 'M/dd/yyyy' ) }}

如预期的那样,过滤器被正确执行,{0}被替换,但是HTML没有被解析

<p>Been caught stealing on 4/20/1977</p>
根据研究,angular恰当地呈现HTML的方式是把它扔到元素的内联ng-bind-html属性中。当我把同样的字符串移动到
<div ng-bind-html="'@Resource.foo' | format: ( ctrl.DateProperty | date: 'M/dd/yyyy' )"></div>

我一无所获。我希望我对这里发生的事情有更深入的了解,但是我的直觉会认为{{实现}}将以与ng-bind-html指令相同的方式评估传递给它的内容。

我如何使用这些过滤器,并得到一个正确解析的HTML块弹出的另一端?

你需要告诉Angular你使用的是HTML,你使用的是trust。否则,它会将其删除。

Angular通过$sce服务提供了这个功能。

您还可以使用ng-bind-html指令

看看这个普朗克有更好的主意。我放置了2个过滤器。

1过滤器注入了$sce并调用.trustAsHtml()方法。另一个没有。

您可以从输出中看到$sce.trustAsHtml(input)允许html。另一个则被Angular完全剥离了。

为简洁起见,柱塞的代码如下:

var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
});
app.filter("formatHtml", ['$sce', function($sce){
  return function(input){
    return $sce.trustAsHtml(input);
  };
}]);
app.filter("NOTformatHtml",function(){
  return function(input){
    return input;
  };
});

html

   <html ng-app="plunker">
  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="angular.js@1.2.x" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.17/angular.min.js" data-semver="1.2.17"></script>
    <script src="app.js"></script>
  </head>
  <body ng-controller="MainCtrl">
    html allowed: <br />
    You have <span ng-bind-html="'<b>Been caught stealing on 4/20/1977</b>' | formatHtml"></span>!
    <br/><br/>
    html stripped out by Angular<br />
    You have <span ng-bind-html="'<b>Been caught stealing on 4/20/1977</b>' | NOTformatHtml"></span>!
  </body>
</html>

最新更新