Chihuahua Enthusiast
Chihuahua Enthusiast

Reputation: 1580

$sce.trustAsHtml Fails on a String

I'm trying to run $sce.trustAsHtml on a string. It throws Error: $sce:itype String Value is Required for SCE Trust Call even though I'm using it on a function that returns a string.

Here's a PLUNKER and the snippet causing the error.

/*****
 * 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;
    }
  }
}

Perhaps there is something wrong with my logic? Or am I using $sce.trustAsHtml incorrectly somehow?

Upvotes: 0

Views: 184

Answers (1)

Caleb Williams
Caleb Williams

Reputation: 1075

I think you're having an issue because you're assigning $scope.image a value and then trusting it. Try:

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

As a side note, if you are wanting to pull in a resource, you should be using trustAsResourceUrl, which you could then use in an ngRepeat. Just so you know you have options.

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

Upvotes: 1

Related Questions