javascript - AngularJS - 从数据中删除\n

标签 javascript json angularjs

捕获和格式化从服务器传递的文本中的“\n\n”以显示换行符的最佳方法是什么? fiddle 在这里:http://jsfiddle.net/nicktest2222/2vYBn/

$scope.data = [{
    terms: 'You agree to be bound be the terms of this site. \n\n Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus tempus lectus ac nunc malesuada, fringilla feugiat nibh rhoncus. Vestibulum adipiscing mi in est consectetur, vitae facilisis nulla tristique. Nam eu ante egestas, ultricies tellus eu, suscipit neque.\n\n Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum et ligula non tellus semper iaculis eget vestibulum metus. Nunc aliquam eros sit amet sapien posuere, ac hendrerit risus ultricies. Vivamus nec enim sed eros placerat pulvinar a quis dui.',
    agreed: false
}];

最佳答案

您还可以使用自定义过滤器来替换 \n<br> .

<p ng-bind-html-unsafe="data[0].terms | nl2br"></p>

还有过滤器。

angular.module('myApp', [])
  .filter('nl2br', function(){
      return function(text) {
           return text ? text.replace(/\n/g, '<br>') : '';
      };
});

** 编辑/更新 - 2014-12-10 **

由于新版本的 Angular 被删除了 ng-bind-html-unsafe @Tamlyn 答案现在是最佳答案。我只是改变了方式$sce为了速度目的被注入(inject)到函数中。

HTML

<p ng-bind-html="data[0].terms | nl2br"></p>

JS

.filter('nl2br', ['$sce', function ($sce) {
    return function (text) {
        return text ? $sce.trustAsHtml(text.replace(/\n/g, '<br/>')) : '';
    };
}]);

jsFiddle

关于javascript - AngularJS - 从数据中删除\n,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18235842/

相关文章:

json - 为嵌套的json数据创建Hive表

angularjs - 带有 Bootstrap 3 的 bower

javascript - 如何为 Node 运行用 typescript 编写的 Jasmine 测试

javascript - 如何计算所见即所得编辑器javascript中的单词数?

javascript - 使用 NodeJS(或 PHP)将 API 数据保存到 JSON 文件

javascript - AngularJs SPA 注销

javascript - 如何去除 Angular 中的悬停效果

javascript - 在 onClickEvent 上将值传递给 ReactJs 中的另一个组件不起作用

javascript - 如何使用 React 从 DOM 中删除 HTML 元素

json - 如何将表单作为 View 模型对象以及其他参数发布到 MVC 中的 Controller ?