2016-11-28 180 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