javascript - AngularJS 将 HTML 传递到 $scope

标签 javascript html angularjs http

我有这些文件:

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 是 promise ,不是字符串。您需要等到 promise 解决后才能获取字符串:

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

关于javascript - AngularJS 将 HTML 传递到 $scope,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33610946/

相关文章:

html - 垂直对齐div中的多个文本框

javascript - 变量是如何在 Angular 工厂中初始化的?

html - 当父 div 改变宽度时设置绝对位置

javascript - 原型(prototype)方法上的 JS Array.prototype.filter

javascript - 将 d3 个圆圈从中心圆圈移开 - 强制布局

javascript - Angularjs:使用路由参数并重新加载

javascript - 向侧面移动三 Angular 箭头

javascript - 如何根据数据库值显示设置访问权限和显示/隐藏div

angularjs - 如何在 if 条件下调用 state.go 时阻止 Controller 的执行?

javascript - 试图从 map() 中获取扁平数据