简体   繁体   中英

ngResource doesn't work when parse HTML from JSON file

I am trying to get blog posts from json file and parse 'description' in HTML format. I use ngResource, but I don't get anything

This is sample data from json

  jsonFeed({
    "title": "My Blog",
    "description": "",
    "modified": "2016-05-10T21:21:46Z",
    "items": [
     {
        "title": "Title1",
        "description": "<p><a href=\"#">Paul<\/a> posted a photo:<\/p> <img src=\"https://farm8.staticflickr.com/7365/26872407641_cfbb210ee7_m.jpg\"/>"
   },
   {
        "title": "Title2",
        "description": " <p><a href=\"#">Beth<\/a> posted a photo:<\/p><img src=\"https://farm8.staticflickr.com/7287/26333398074_cfbce73532_m.jpg\" />"
   }
  ]
  })

app.js

 var app = angular.module('blogApp',['ngResource']);
 app.filter("sanitize", ['$sce', function($sce) {
   return function(htmlCode){
    return $sce.trustAsHtml(htmlCode);
  }
 }]);
 app.controller('BlogController', ['$http', '$scope', function($http, $scope){
var blog = this;
blog.posts = {};
  $http.jsonp('url').success(function(data){ 
});
jsonFeed = function(data){
$scope.posts = data.items;
}

index.html

  <body ng-app="blogApp">
    <div ng-controller="BlogController as blog">
        <div class="post" ng-repeat="post in posts">
            <h2>{{post.title}}</h2>
            <div ng-bind-html="'{{post.description}}' | sanitize"></div>
    </div>
    <script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
    <script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.2/angular.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.0/angular-resource.js"></script>
    <script src="app.js" type="text/javascript"></script>
</body>

In the result I just get this

   {{post.description}}

Also tried to inspect element in console

  <div ng-bind-html="'<p><a href="#">Paul<\/a> posted a photo:<\/p> <img src=\"https://farm8.staticflickr.com/7365/26872407641_cfbb210ee7_m.jpg\"/>' | sanitize" class="ng-binding">{{post.description}}</div>

Why can't I parse and see html of description?

Do use controller alias blog , when you are referring posts to looping over it.

<div class="post" ng-repeat="post in blog.posts">

And then

<div ng-bind-html="post.description | sanitize"></div>

Note : I can't see any ngResource related code there in your question. Do you missed anything to add in question?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM