2016-11-28 173 views
1

我已经开发了一个使用Moodle WebService的AngularJS Moodle webapp,并且我正在试图从Moodle eLearning展示一个测验。将JSON HTML字符串转换为HTML

我可以使用$http.得到每个问题。现在的问题是,当我得到的问题,每一个问题带有一个HTML代码:

JSON Response

的我使用这个controlores得到响应(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> 

Error

而且,我试着用:

JSON.stringify 
angular.fromJson(json); 

当我使用这个线{{question.html}}<br /><br />,我得到这个:

With regular line

感谢您的帮助!

+1

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

回答

1

我认为你需要的严格的语境逃逸服务$sce)。 这是一项服务,使您可以指定它是O.K的上下文。允许任意的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}} 
+0

如果我像使用'ng-repeat'一样使用它不起作用。 – rfcabal

+0

O.K.提到这个答案http://stackoverflow.com/questions/24459194/angularjs-using-sce-trustashtml-with-ng-repeat,它解释了如何解决这个问题。还更新了我的答案。 – frishi

+0

我必须使用这个过滤器'.filter(“sanitize”,['$ sce',function($ sce){return function(htmlCode){ return $ sce。trustAsHtml(htmlCode); } }])'感谢您的帮助! – rfcabal

1

您需要使用$sce服务

$sce.trustAsHtml(varWithHTML) 

作出具有约束力的HTML工作。

由于文档说https://docs.angularjs.org/api/ng/service/ $ SCE

+0

我尝试了一个像'$ scope.questions2 = $ sce.trustAsHtml(response.data.questions [0] .html)'这样的特定变量,但是如果你尝试过'''scope.questions = response.data。问题',ng-repeat'不起作用。 – rfcabal