【问题标题】:decoding the html tag from response and showing it in view从响应中解码 html 标记并将其显示在视图中
【发布时间】:2018-06-11 08:02:13
【问题描述】:

我下面给出的响应是编码格式,我正在使用过滤器对其进行解码并在我的 html 中显示值。但我需要在我的视图中将它们显示为 html。所以使用了trustAsHtml。但这里的问题是当我使用 trustAsHtml 时,我的解码不会发生。它显示异常意外令牌。

 $scope.res=  "data": [
                {
                  "jd": "<p>this jd1</p>"
                },
                {
                  "jd": "<li>this jd2</li>"
                },
                {
                  "jd": "<ul>this jd3</ul>"
                },
                {
                  "jd": "<p>this jd4</p>"
                }
              ]
            }   

JS:

$scope.trustAsHtml = $sce.trustAsHtml;

过滤器:

 app.filter('decodeFilter', function() {
    return function(input) {
        return decodeURIComponent(unescape(input));
    };
});

HTML:

     <div ng-repeat="item in res">
        <div ng-bind-html ="trustAsHtml(item.jd | decodeFilter)">
</div>

【问题讨论】:

    标签: angularjs ng-bind-html decodeuricomponent


    【解决方案1】:

    您的 ng-repeat 对象 res 似乎有问题,您应该根据您的代码使用 res.data。我也对您的自定义过滤器进行了一些更正。您也可以查看this plunker 以获得您给定的工作示例。

    模板:

    <div ng-repeat="item in res.data">
      <div ng-bind-html ="item.jd | decodeFilter"></div>
    </div>
    

    控制器:

    app.controller('MainCtrl', function($scope) {
      $scope.res = {
        "data": [ {
            "jd": "<p>this jd1</p>"
          }, {
            "jd": "<li>this jd2</li>"
          }, {
            "jd": "<ul>this jd3</ul>"
          }, {
            "jd": "<p>this jd4</p>"
          }]
      };
    });
    app.filter('decodeFilter', function($sce) {
        return function(input) {
            return $sce.trustAsHtml(decodeURIComponent(input));
        };
    });
    

    注意: unescape() 函数在 JavaScript 1.5 版中已弃用。请改用 decodeURI() 或 decodeURIComponent()。 这意味着 unescape 等于 decodeURLComponent。

    【讨论】:

    • 在您的回答中,您删除了过滤器中的 decodeURIComponent。那么解码是如何发生的
    • 在您的响应对象中,它们都没有被编码,这就是我从过滤器中删除 decodeURIComponent 的原因。您可以根据需要添加它,因为我已经更新了答案和带有 decodeFilter 的 plunker。
    【解决方案2】:

    您是否尝试过像这样使用 $sceProvider 在 app.config 中启用它?

    angular
    .module('myapp')
    .config(["$locationProvider", "$sceProvider",function config($locationProvider, $sceProvider) {
            $sceProvider.enabled(true);
            $locationProvider.html5Mode(true);
    });
    

    【讨论】:

      猜你喜欢
      • 2012-11-02
      • 2014-07-06
      • 1970-01-01
      • 1970-01-01
      • 2013-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-31
      相关资源
      最近更新 更多