【问题标题】:Formatting JSON String Into Paragraphs将 JSON 字符串格式化为段落
【发布时间】:2017-09-21 19:56:14
【问题描述】:

我正在将 Angular JS 用于一个简单的网络应用程序。

我有一个包含多个段落的 JSON 对象。因此,我需要将段落分成两行。我做了一些研究,找到了类似问题的一些答案,但由于没有将它们放在上下文中,我不理解它们。我试图查看 JSON 是否内置了强制换行的内容,因为那样可以,但我没有找到。

非常感谢您的帮助!

带有 Angular JS 的 HTML

<div class="bio">
    {{exhibits[whichItem].bio}}
</div>

JSON

[
  {
    "name":"Name goes here",
    "bio":"First long block of text goes here then it needs a break <br /> and the second long block of text is here."
  }
]

AngularJS - controllers.js

var exhibitListControllers = angular.module('exhibitListControllers', ['ngAnimate']);

exhibitListControllers.controller('ListController', ['$scope', '$http', function($scope, $http){
  $http.get('js/data.json').success(function(data) {
  $scope.exhibits = data;
  $scope.exhibitOrder = 'name';
 });
}]);

【问题讨论】:

    标签: javascript html angularjs json


    【解决方案1】:

    来自https://docs.angularjs.org/api/ng/directive/ngBindHtml

    https://docs.angularjs.org/api/ngSanitize

    ng-bind-html 计算表达式并以安全的方式将生成的 HTML 插入到元素中。默认情况下,生成的 HTML 内容将使用 $sanitize 服务进行清理。要利用此功能,请确保 $sanitize 可用,例如,通过将 ngSanitize 包含在模块的依赖项中(不在核心 AngularJS 中)。为了在模块的依赖项中使用 ngSanitize,您需要在应用程序中包含“angular-sanitize.js”。

    在html页面中你可以这样做

    <div ng-controller="ExampleController">
       <p ng-bind-html="myHTML"></p>
    </div>
    

    在你的控制器中:

    angular.module('bindHtmlExample', ['ngSanitize'])
    .controller('ExampleController', ['$scope', function($scope) {
     $scope.myHTML =
       'I am an <code>HTML</code>string with ' +
       '<a href="#">links!</a> and other <em>stuff</em>';
    }]);
    

    你也可以试试这样的:

    app.filter('to_trusted', ['$sce', function($sce) { 返回函数(文本){ 返回 $sce.trustAsHtml(文本); }; }]);

    然后,在视图中:

    ng-bind-html="myHTML | to_trusted"

    【讨论】:

    • 感谢您发送此信息!我正在尝试遵循这一点,尽管我认为我理解它,但我正在努力将它与我当前的控制器结合起来。我将 Angular JS - controllers.js 添加到我的问题中,以更好地阐明我当前的设置,并为这个答案找到一些额外的指导。
    • 在 $scope.myHTML 中它引用了一个字符串,但这个字符串是 JSON 文件中 JSON 对象的一部分。我不确定如何合并它。
    • 我没有尝试过你的代码,但我认为这可能并不重要,它应该适用于 JSON 或非 JSON 字符串。
    • 不幸的是,它只是删除了 JSON bio 并用括号显示它:{{exhibits[whichItem].bio}}。将有 9 个这样的对象,其中一个具有 HTML 格式的只是 bio 键。
    猜你喜欢
    • 2015-06-30
    • 1970-01-01
    • 2020-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-02
    • 2023-01-19
    相关资源
    最近更新 更多