简体   繁体   English

如何在Angular的JSON属性中绑定HTML数据

[英]How to bind HTML data in JSON property in Angular

My JSON looks like: 我的JSON看起来像:

[
  {
    "Title": "MyTitle1",
    "Content": "<p>Content1</p>",
    "Date": "2014-11-19T10:00:00"
  },
  {
    "Title": "MyTitle2",
    "Content": "<p>Content2</p>",
    "Date": "2014-11-19T00:00:00"
  }
]

I'm getting it in my controller like this: 我在我的控制器中这样得到它:

app.controller('NewsfeedCtrl', function ($scope, $http) {
    $http.get(serverAddress + '/api/newsfeed/page/1').
      success(function (data, status, headers, config) {
          $scope.newsfeeds = data;
      }).
      error(function (data, status, headers, config) {
          console.log("Smth went wrong.");
      });
});

And bind it in view: 并将其绑定到视图中:

<div ng-controller="NewsfeedCtrl">
    <div ng-repeat="newsfeed in newsfeeds">
        {{newsfeed.Title}}
        <br />-
        <br />{{newsfeed.Date}}
        <br />-
        {{newsfeed.Content}}
    </div>
</div>

But if I have HTML tags in Content, how can I have it also binded to view with that tags parsed. 但是,如果我在Content中有HTML标记,那么如何将其也绑定到具有已解析的标记的视图。

Use ng-bind-html to handle content as html content. 使用ng-bind-html将内容作为html内容处理。

<div ng-controller="NewsfeedCtrl">
    <div ng-repeat="newsfeed in newsfeeds">
        {{newsfeed.Title}}
        <br />-
        <br />{{newsfeed.Date}}
        <br />-
        <div ng-bind-html="newsfeed.Content"></div>
    </div>
</div>

Also don't forget to include ngSanitize module in your application like this. 同样不要忘记像这样在您的应用程序中包含ngSanitize模块。

angular.module('itadPortal', ['ngRoute', 'ngSanitize']);

You can read more about ng-bind-html HERE . 您可以在此处阅读有关ng-bind-html的更多信息。

使用ngBindHtml

<span ng-bind-html="newsfeed.Content"></span>

Instead of loading the HTML tags as part of Content, just replace them with the name (eg just "Content2") and load them inside ap tag. 除了将HTML标签作为Content的一部分加载之外,只需将其替换为名称(例如,仅“ Content2”),然后将其加载到ap标签中即可。 So your JSON would look like: 因此,您的JSON如下所示:

[
  {
    "Title": "MyTitle1",
    "Content": "Content1",
    "Date": "2014-11-19T10:00:00"
  },
  {
    "Title": "MyTitle2",
    "Content": "Content2",
    "Date": "2014-11-19T00:00:00"
  }
]

and your view should contain this line: 并且您的视图应包含以下行:

<p> {{newsFeed.content}} </p>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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