javascript - 将 JSON 字符串格式化为段落

标签 javascript html angularjs json

我正在使用 Angular JS 来构建一个简单的 Web 应用程序。

我有一个包含多个段落的 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 - Controller .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';
 });
}]);

最佳答案

来自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>

在你的 Controller 中:

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) {
      return function(text) {
        return $sce.trustAsHtml(text);
      };
    }]);

然后,在 View 中:


    ng-bind-html=" myHTML | to_trusted"

关于javascript - 将 JSON 字符串格式化为段落,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46352238/

相关文章:

html - 4个Divs彼此相邻,且高度相同,并在其下方填充

jquery - script-tutorials.com Colorwheel改变不同div的颜色

javascript - angularjs:无法显示JS的返回值 `typeof`

javascript - 模态窗口未激活

javascript - 内爆阵列未按预期工作

php - Wordpress 在选择自定义字段时应用特定的 css

javascript - Angular.js 框架的附加 js 文件有什么用?

javascript - 使用拼接从数组中删除对象

javascript - 如何安全地打印带有 HTML 标签和实体的字符串

javascript - 你能动态创建一个 IMG 元素,并使用 document.GetElementById(name); 访问它吗?