繁体   English   中英

AngularJS将HTML传递到$ scope

[英]AngularJS passing HTML into $scope

我有这些文件:

的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>

我如何将HTML放入$ scope然后将其插入到html中?

我收到一个错误,说$ sce需要一个字符串参数,但我认为我传递给它的应该是一个字符串。

oneFac和twoFac是承诺,而不是字符串。 您需要等到promises解决才能获得字符串:

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服务有助于呈现HTML内容。

示例代码

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

你必须在控制器中注入$ sce

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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