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

时间:2013-12-08 16:52:44

标签: javascript html json angularjs

我正在尝试使用AngularJS 1.1.5和PHP构建一个推荐网站

我有一个JSON对象数组,包括Name,Message和Date。

真实的推荐将是消息属性,并且推荐书中会有换行符。

[
{
    "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"
}
]

使用$ 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>

但是,我无法在html页面中正确呈现换行符。有谁知道我该怎么做?

谢谢

2 个答案:

答案 0 :(得分:6)

试试这个:

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

答案 1 :(得分:0)

正如epascarello所说,ngBindHtml处理得很好。我不确定它在1.1.5中的位置,但它使用$santize服务来处理转义。根据文档,如果$santize不可用,它会抛出异常而不是允许利用。