如何使用AngularJS解析HTML?我试图构建一个这样的过滤器:
gameApp.filter('unsafe', function($sce) {
return function(val) {
return $sce.trustAsHtml(val);
};
});
我在我的观点中这样使用它:
<div ng-controller="gameCtrl">
<table>
<p ng-bind-html="result | unsafe"></p>
</tr>
</table>
</div>
但那不起作用。结果包含我想用我的表填充的tr和td标签。
这是我的控制器:
var gameApp = angular.module("gameApp", ['ngRoute']);
gameApp.service('link', function() {
this.user = false;
});
gameApp.filter('unsafe', function($sce) {
return function(val) {
return $sce.trustAsHtml(val);
};
});
function makeTableFrom(str) {
var k = 1;
result = "";
for(var i = 1; i <= 8; i++) {
result += '<tr>';
for(var j = 1; j <= 20; j++) {
if(str[k] === '#') {
result += '<td id=' + k + '">#</td>';
}
else if(str[k] === '&') {
result += '<td class="click" val="water" id="' + k + '">&</td>';
}
else {
result += '<td class="click" id="' + k + '"><a href="#"></a></td>';
}
k++;
}
result += '</tr>';
}
return result;
}
gameApp.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl : 'partials/firstpage.html',
controller : 'firstPageCtrl'
})
.when('/game', {
templateUrl : 'partials/game.html',
controller : 'gameCtrl'
});
});
gameApp.controller("firstPageCtrl", function($scope,$http,link,$location) {
$scope.doLogin = function() {
$http.post("lib/action.php", {username: $scope.username, password: $scope.password}).success(function(data) {
if(data) {
link.user = data;
console.log(link.user);
$location.path("/game");
}
}).error(function(data) {
console.log(data);
});
};
});
gameApp.controller("gameCtrl", function($scope,$http,link,$location) {
//$scope.trr = [1,2,3,4,5,6,7,8];
//$scope.tdd = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];
$scope.getMonsters = "1";
var map;
$http.post("lib/action.php", {monsters: $scope.getMonsters}).success(function(data) {
map = data;
console.log(map);
$scope.result = makeTableFrom(data);
console.log($scope.result);
});
if(link.user) {
/*$scope.message = "fisk";
console.log(link.user);*/
} else {
/*$scope.message = "Ledsen fisk";
console.log("Är inte satt");*/
}
});
任何可以帮助我的人?
答案 0 :(得分:1)
理想情况下,您将使用模板或视图显示HTML并将数据传递给这些模板或视图。除了实时代码编辑器之外,显示原始HTML还会打开XSS和其他安全漏洞。