1

I have these files:

index.html

//contains logic about passing arguments to the app.js btnClick function
<div ng-bind-html="currentDisplay"></div>

app.js

app.factory('oneFac', function ($http){
var htmlCode = null;
htmlCode = $http.get("one.html").then(function (response){
    return response.data;
});
    return htmlCode;
});

app.factory('twoFac', function ($http){
var htmlCode = null;
htmlCode = $http.get("two.html").then(function (response){
    return response.data;
});
    return htmlCode;
});

app.controller('mainCtrl', function ($scope, oneFac, twoFac, $sce){
  $scope.one = oneFac;
  $scope.two = twoFac;
  $scope.currentDisplay = $sce.trustAsHtml($scope.one);
  $scope.btnClick = function (selection){
    if(selection == "one"){
      $scope.currentDisplay = $sce.trustAsHtml($scope.one);
    }
    else if(selection == "two"){
      $scope.currentDisplay = $sce.trustAsHtml($scope.two);
    }
  }
});

one.html

<p>one</p>

two.html

<p>two</p>

How could I get the HTML into the $scope then have it inserted into the html?

I am getting an error saying $sce requires a string argument, but I thought what I am passing to it should be a string.

3
  • try using ng-bind-html or ng-include if you only need to load html files Commented Nov 9, 2015 at 14:13
  • Sorry, I actually already had this in the code, but I understand the ng-include part, but these two views can't be on the html page at the same time. Commented Nov 9, 2015 at 14:17
  • maybe take a look at the example at the bottom of the documentation Commented Nov 9, 2015 at 14:18

2 Answers 2

2

oneFac and twoFac are promises, not strings. You need to wait until the promises resolve to get the strings:

app.controller('mainCtrl', function ($scope, $q, oneFac, twoFac, $sce){
  // waiting until both are resolved, then setting the rest of the controller.
  // You may still want to initialize part of the controller before your promises resolve
  // change accordingly
  $q.all([oneFac, twoFac]).then(function (promises) {
    var oneHtml = promises[0],
        twoHtml = promises[1];

    $scope.one = oneHtml;
    $scope.two = twoHtml;
    $scope.currentDisplay = $sce.trustAsHtml($scope.one);
    $scope.btnClick = function (selection){
      if(selection == "one"){
        $scope.currentDisplay = $sce.trustAsHtml($scope.one);
      }
      else if(selection == "two"){
        $scope.currentDisplay = $sce.trustAsHtml($scope.two);
      }
    }
  });
});
Sign up to request clarification or add additional context in comments.

Comments

1

$sce service helps to render html content.

sample code

$scope.htmldisplay = $sce.trustAsHtml(data);

you have to inject $sce in your controller

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.