簡體   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