2015-10-30 80 views
0

我試圖在字符串上運行$sce.trustAsHtml。它拋出Error: $sce:itype String Value is Required for SCE Trust Call,即使我使用它返回一個字符串的函數。

這裏是PLUNKER和導致錯誤的代碼片段。

/***** 
* Should display two images 
* *****/ 
$scope.image = determineNeverSettleImage("engaging,innovative"); 
$scope.image = $sce.trustAsHtml($scope.image); 

/************ 
* This function should: 
* return 3 images if passed "engaging,innovating,partnering", 
* return 2 images if passed "engaging,innovating", 
* return 1 image if passed "engaging" 
**************/ 
function determineNeverSettleImage(neverSettle) { 
    if (neverSettle.split(",").length > 1) { 
    neverSettleArray = neverSettle.split(","); 
    neverSettleStr = ""; 
    for (i = 0; i < neverSettleArray.length; i++) { 
     if (neverSettleArray[i] == "engaging") { 
     neverSettleStr += '<img src="http://lorempixel.com/400/200/" width="56px" height="56px">'; 
     } 
     if (neverSettleArray[i] == "innovating") { 
     neverSettleStr += '<img src="http://lorempixel.com/400/200/" width="56px" height="56px">'; 
     } 
     if (neverSettleArray[i] == "partnering") { 
     neverSettleStr += '<img src="http://lorempixel.com/400/200/" width="56px" height="56px">'; 
     } 
     if (neverSettleArray[i] == "synergy") { 
     neverSettleStr += '<img src="http://lorempixel.com/400/200/" width="56px" height="56px">'; 
     } 
    } 
    $scope.test = neverSettleStr; 
    neverSettleStr = neverSettleStr + ''; 
    return neverSettleStr; 
    } else { 
    switch (neverSettle) { 
     case "engaging": 
     neverSettle = '<img src="http://lorempixel.com/400/200/" width="56px" height="56px">'; 
     return neverSettle; 
     case "innovating": 
     neverSettle = '<img src="http://lorempixel.com/400/200/" width="56px" height="56px">'; 
     return neverSettle; 
     case "partnering": 
     neverSettle = '<img src="http://lorempixel.com/400/200/" width="56px" height="56px">'; 
     return neverSettle; 
     case "synergy": 
     neverSettle = '<img src="http://lorempixel.com/400/200/" width="56px" height="56px">'; 
     return neverSettle; 
    } 
    } 
} 

也許我的邏輯有問題嗎?或者我是否錯誤地使用$sce.trustAsHtml

+0

這可能是一個很好的參考http://stackoverflow.com/questions/18340872/how-do-you-use-sce-trustashtmlstring-to-replicate-ng-bind-html-unsafe-in- angu – ArslanW

回答

1

我認爲你遇到了問題,因爲你正在爲$scope.image分配一個值,然後相信它。嘗試:

$scope.image = $sce.trustAsHtml(determineNeverSettleImage("engaging,innovative")); 

作爲一個側面說明,如果你想要在資源來拉,你應該使用trustAsResourceUrl,然後你可以在ngRepeat使用。只是讓你知道你有選擇。

$scope.image = $sce.trustAsResourceUrl(); 
+0

謝謝@Caleb,當我有空時,我會試試這個。 – chakeda