$ sce.trustAsHtml在字符串上失败

时间:2015-10-30 20:42:29

标签: javascript angularjs

我试图在字符串上运行$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

1 个答案:

答案 0 :(得分:1)

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

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

作为旁注,如果您想要提取资源,则应该使用trustAsResourceUrl,然后可以在ngRepeat中使用$scope.image = $sce.trustAsResourceUrl(); 。只是因为你知道你有选择。

class NavigationBar extends Navigator.NavigationBar {
  render() {
    var routes = this.props.navState.routeStack;

    if (routes.length) {
      var route = routes[routes.length - 1];

      if (route.display === false) {
        return null;
      }
    }

    return super.render();
  }
}