我正在尝试在字符串上运行$sce.trustAsHtml。即使我在返回字符串的函数上使用它,它也会抛出Error: $sce:itypeString 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

最佳答案

我认为您遇到了问题,因为您要为$scope.image分配一个值,然后再信任它。尝试:

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


附带说明一下,如果要提取资源,则应使用trustAsResourceUrl,然后可以在ngRepeat中使用。只是您知道自己有选择。

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

关于javascript - $ sce.trustAsHtml在字符串上失败,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33444583/

10-10 00:36