【问题标题】:Format html from json从 json 格式化 html
【发布时间】:2015-06-01 00:09:13
【问题描述】:

我是 AngularJs 的初学者,这是我的第一次尝试

我正在尝试显示来自 json 链接的数据,并且某些字段包含 html

这里是json内容:

[{"titre":"Titre18","description":"<p>test<\/p>"},{"titre":"Titre18f","description":"<p>sdfsdfsd<\/p>"}]

我使用这个 angularJs 代码来显示数据

<div ng-app="myApp" ng-controller="customersCtrl"> 

<ul>
  <li ng-repeat="x in names">
    {{x.titre}}
    {{x.description}}
  </li>
</ul>

</div>

<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
  $http.get("JSONLINK")
  .success(function (response) {$scope.names = response;});
});
</script>

问题是,字段描述显示在 json 中:

 - Titre18 <p>test</p> 
 - Titre18f <p>sdfsdfsd</p>

是否可以将此字段格式化为 html ? 我希望 p 标签被解释为 html

我使用 angularJs 1.3.15

非常感谢

【问题讨论】:

标签: json angularjs


【解决方案1】:

试试这个:

<ul>
  <li ng-repeat="x in names" ng-bind-html="x.description">
    {{x.titre}}
    {{x.description}}
  </li>
</ul>

现在请注意 ng-bind-html 将评估“描述”内容中的 HTML 并“安全地”呈现它,如果你想绕过 Angular 的 sanitize 方法,还有 ng-bind-html-unsafe 。但使用时要小心,考虑到错误的“>”符号可能会破坏整个页面。

您还需要在模块上添加对 ngSanitize 的依赖项。

angular.module('yourmodule', ['ngSanitize']);

需要 angular-sanitize.js 文档:https://docs.angularjs.org/api/ngSanitize

这里是 bind-html 的文档 https://docs.angularjs.org/api/ng/directive/ngBindHtml

【讨论】:

  • 当我尝试这个时没有显示任何内容
  • 试了不安全,还是有

  • 在 ng-bind-html 中尝试 x.description。
  • 得到这个错误:错误:[$injector:unpr] errors.angularjs.org/1.3.15/$injector/… at Error (native)
  • @user 尝试将 ngSanitize 依赖项添加到您的模块中,如果我没记错的话,您还必须包含 angular-sanitize.js。
【解决方案2】:

这里是 plunker 的代码链接。a link!

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Example - example-example62-production</title>


  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.0-beta.6/angular.min.js"></script>
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.0-beta.6/angular-sanitize.js"></script>
  <script src="script.js"></script>



</head>
<body ng-app="bindHtmlExample" >
  <div ng-controller="ExampleController">
 <ul>
  <li ng-repeat="x in names" ng-bind-html="x.description">
    {{x.titre}}
    {{x.description}}
  </li>
</ul>
</div>
</body>
</html>

在 script.js 中

(function(angular) {
  'use strict';
angular.module('bindHtmlExample', ['ngSanitize'])
  .controller('ExampleController', ['$scope', function($scope) {
    $scope.names =[{"titre":"Titre18","description":"<p>test<\/p>"},{"titre":"Titre18f","description":"<p>sdfsdfsd<\/p>"}];
  }]);
})(window.angular);

在这里你会看到 p 标签被解释为 html 而不是字符串。希望这会对你有所帮助

【讨论】:

    【解决方案3】:

    如果我理解正确,你想剥离

    描述文本周围的

    标记。见此链接:angularjs to output plain text instead of html

    【讨论】:

    • 对不起,如果我的信息不清楚。我不想剥离html,我想被解释
    猜你喜欢
    • 1970-01-01
    • 2020-06-03
    • 2020-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-23
    • 2021-05-26
    • 1970-01-01
    相关资源
    最近更新 更多