我有这些文件:
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/