angularjsng-bind-htmldecodeuricomponent

decoding the html tag from response and showing it in view


My below given response comes as encoded format , i am decoding it using a filter and displaying value in my html . But I need to display them as html in my view. So trustAsHtml has been used. but the problem here is when I use trustAsHtml my decoding doesn't occur.it shows exception unexpected token.

 $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;

Filter:

 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>

Solution

  • There seems to be issue with your ng-repeat object res, you should use res.data as per your code. I have made some correction from your custom filter as well. Also you can check this plunker for your given working example.

    Template:

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

    Controller:

    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));
        };
    });
    

    Note: The unescape() function was deprecated in JavaScript version 1.5. Use decodeURI() or decodeURIComponent() instead. Which means unescape is equal to decodeURLComponent.