Raduken Raduken - 3 months ago 22
JSON Question

Angular.js How to render a HTML tag from json file

I am trying to parse html value in my angular page, not sure what I am doing wrong, I am getting this error in my console:


app.js:13 Uncaught SyntaxError: Unexpected token )


app.js

var App = angular.module('App', []);

App.controller('ProjectCtrl', function($scope, $http) {
$http.get('app/test.json')
.then(function(res){
$scope.projects = res.data;
});

App.filter('to_trusted', ['$sce', function($sce){
return function(text) {
return $sce.trustAsHtml(text);
};
});


test.json

[
{ "icon": "<i class="fa fa-github fa-3x" aria-hidden="true"></i>", "name": "lovelycss" },
{ "icon": "<i class="fa fa-github fa-3x" aria-hidden="true"></i>", "name": "lovely-icons" }
]


html:

<div ng-controller="ProjectCtrl">
<ul>
<li ng-repeat="project in projects">
<div ng-bind-html="'{{project.icon}}' | to_trusted"></div>- <em>{{project.name}}</em>
</li>
</ul>
</div>


what I am trying to archive is this: http://jsfiddle.net/JfGVE/1547/

I want a json loading the icons and the text.

I hope now this will be clear.

Answer

You are missing a } in your controller declaration and a [ in your filter declaration:

var App = angular.module('App', []);

App.controller('ProjectCtrl', function($scope, $http) {
    $http.get('app/test.json')
         .then(function(res){
            $scope.projects = res.data;
          });
}); // You are missing a '}' here

App.filter('to_trusted', ['$sce', function($sce){
    return function(text) {
        return $sce.trustAsHtml(text);
    };
}]); // You are missing a ']' here

You will also have to edit your JSON to escape your quotes "

[
    {
        "icon": "<i class=\"fa fa-github fa-3x\" aria-hidden=\"true\"></i>",
        "name": "lovelycss"
    }, {
        "icon": "<i class=\"fa fa-github fa-3x\" aria-hidden=\"true\"></i>",
        "name": "lovely-icons"
    }
]

And the expression you are passing to ng-bind-html is also wrong. Because of the single quotes ' you are passing a literal string '{{project.icon}}' to the filter. You have to remove the quotes and the curly braces, because the ng-bind-html directive needs an expression as a parameter.

<div ng-controller="ProjectCtrl">
  <ul>
    <li ng-repeat="project in projects">
     <div ng-bind-html="project.icon | to_trusted"></div>- <em>{{project.name}}</em>
    </li>
  </ul>
</div>