我有这些文件:
的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需要一个字符串参数,但我认为我传递给它的应该是一个字符串。
答案 0 :(得分:2)
oneFac和twoFac是承诺,而不是字符串。您需要等到承诺解决才能获得字符串:
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);
}
}
});
});
答案 1 :(得分:1)