0

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>
NTP
  • 4,338
  • 3
  • 16
  • 24
Nicoleta Wilskon
  • 687
  • 1
  • 10
  • 32

2 Answers2

1

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.

Immanuel Kirubaharan
  • 1,094
  • 1
  • 11
  • 17
  • in your answer , you removed decodeURIComponent in filter. so how does decoding occurs – Nicoleta Wilskon Jun 11 '18 at 08:22
  • In your response object none of them are encoded that's the reason I've removed the decodeURIComponent from the filter. You can add it if you want as I have updated answer and the plunker with the decodeFilter. – Immanuel Kirubaharan Jun 11 '18 at 08:41
0

have you tried to enable it in the app.config with the $sceProvider like this?

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