【问题标题】:Convert JSON HTML string to HTML将 JSON HTML 字符串转换为 HTML
【发布时间】:2016-11-28 18:43:03
【问题描述】:

我已经使用 Moodle WebService 开发了一个 AngularJS Moodle webapp,我正在尝试展示 Moodle eLearning 中的一个测验。

我可以使用$http. 解答所有问题。现在的问题是,当我收到问题时,每个问题都带有这样的 HTML 代码:

我正在使用此控制器来获取 响应 (url5)

app.controller('quizCtrl', function($rootScope, $scope, $http) {

url4 = concatUrl + 'mod_quiz_start_attempt' + '&quizid=2'; 

$http.get(url4).then(function (response) {
                    //console.log(response.data); 
                })

url5 = concatUrl + 'mod_quiz_get_attempt_data' + '&attemptid=7&page=0'; 

$http.get(url5).then(function (response) {
                    console.log(response.data);
                    $scope.questions = response.data.questions;
                })
})

当我使用以下代码在 HTML 中显示问题时,我将 HTML 代码作为字符串获取并尝试使用 ng-bind-html 但出现错误。

<div role="main" id="main" class="ui-content scroll" ng-app="mainApp">
<div data-role="content" class="pane" id="">
    <div class="page-wrap scroll" ng-controller="quizCtrl">
          <div ng-repeat="question in questions | orderBy : 'question.number'" id="{{question.number}}">
            <div>
                <!--{{question.html}}<br /><br />-->
                <p ng-bind-html="question.html"> </p><br /><br /> 
            </div>
          </div> 
    </div>
</div>

另外,我尝试过:

JSON.stringify
angular.fromJson(json);

当我使用这行 {{question.html}}&lt;br /&gt;&lt;br /&gt; 时,我得到了这个:

感谢你们的帮助!

【问题讨论】:

  • 如果你使用 'angular.js' 而不是 'angular.min.js' 你会看到错误文本,而不是链接。 :)

标签: javascript jquery html angularjs json


【解决方案1】:

我认为您需要严格的上下文转义服务 ($sce)。 这是一项服务,使您能够指定它是正常的上下文。允许任意 HTML。

文档:https://docs.angularjs.org/api/ng/service/$sce

将其注入您的控制器中:

app.controller('quizCtrl', function($rootScope, $scope, $http, $sce) 
...
$http.get(url5).then(function (response) {
    console.log(response.data);
    $sce.trustAsHtml = $sce.trustAsHtml; // <- needs to be exposed on $scope
    $scope.questions = $sce.trustAsHtml(response.data.questions);
})
...

在你看来:

{{questions}}

【讨论】:

  • 好的。参考这个答案stackoverflow.com/questions/24459194/…,它解释了如何解决这个问题。也更新了我的答案。
  • 我必须使用这个过滤器.filter("sanitize", ['$sce', function($sce) { return function(htmlCode){ return $sce.trustAsHtml(htmlCode); } }])谢谢你的帮助!
  • 当然,创建过滤器是一种方法。本质上,您不能在表达式中使用$sce.trustAsHtml
【解决方案2】:

你需要使用$sce服务

$sce.trustAsHtml(varWithHTML)

使绑定 html 工作。

正如文档所说 https://docs.angularjs.org/api/ng/service/$sce

【讨论】:

  • 我尝试使用 $scope.questions2 = $sce.trustAsHtml(response.data.questions[0].html) 之类的特定变量,但如果您尝试使用 , $scope.questions = response.data.questions, ng-repeat 则不起作用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-29
  • 1970-01-01
  • 1970-01-01
  • 2016-07-19
  • 2011-03-09
相关资源
最近更新 更多