简体   繁体   中英

AngularJS passing HTML into $scope

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.

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);
      }
    }
  });
});

$sce service helps to render html content.

sample code

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

you have to inject $sce in your controller

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM