简体   繁体   English

如何将换行符从JSON渲染到HTML

[英]How to render line breaks from JSON to HTML

I am trying to build a testimonial website with AngularJS 1.1.5 and PHP 我正在尝试使用AngularJS 1.1.5和PHP构建一个推荐网站

I have an array of JSON objects consisting of Name, Message and Date. 我有一个由Name,Message和Date组成的JSON对象数组。

The real testimonial will be the attribute Message and there will be line breaks in the testimonial. 真实的推荐将是Message属性,并且在推荐书中会有换行符。

[
{
    "Name": "Snow White",
    "Message": "Dear all, I need a new line <br> Is it possible to do it in AngularJS?",
    "Date": "16/11/2013"
},
{
    "Name": "Cinderalla",
    "Message": "Dear all, I need a new line <br> Is it possible to do it in AngularJS?",
    "Date": "10/11/2013"
},
{
    "Name": "Ariel",
    "Message": "Dear all, I need a new line <br> Is it possible to do it in AngularJS?",
    "Date": "20/06/2013"
}
]

After using $resource to get the array and link it to $scope.Ctestimonials, I used ng-repeat to render all the objects onto HTMl. 在使用$ resource获取数组并将其链接到$ scope.Ctestimonials之后,我使用ng-repeat将所有对象渲染到HTMl上。

<div id="testimonialbody" ng-controller="TestimonialCtrl">
<ul class="testimonialul">
<li ng-repeat="testimonial in Ctestimonials" class="testimonialclass">
<blockquote> {{testimonial.Message}}
</blockquote>
<cite>{{testimonial.Name}}, {{testimonial.Date}}</cite>
</li>
</ul>
</div>

However, I could not get the line breaks to render correctly in the html page. 但是,我无法在html页面中正确呈现换行符。 Does anyone know how can I do it? 有谁知道我该怎么做?

Thank you 谢谢

Try this: 试试这个:

JSON.stringify({{testimonial.Name}},null,'\t')
    .replace(/\n/g,'<br />')
    .replace(/\t/g,'&nbsp;&nbsp;&nbsp;');

As epascarello said, ngBindHtml handles this nicely. 正如epascarello所说, ngBindHtml处理得很好。 I'm not sure where it stood in 1.1.5, but it uses the $santize service to handle escaping. 我不确定它在1.1.5中的位置,但它使用$santize服务来处理转义。 Per the docs, if $santize isn't available, it throws an exception rather than allowing an exploit. 根据文档,如果$santize不可用,它会抛出异常而不是允许利用。

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

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