我是 AngularJS 的新手。我在更改 table
的内部 HTML 时遇到困难。我将一个字符串存储在一个变量中,该字符串包括 3
类型的标签 strong
标签这很好用,还有两个标签 tr
和 td
当我用 JavaScript 变量替换表的内部值时,它不会将 tr
和 td
标记转换为 DOM 元素。
这是我的 JavaScript 代码:
var app = angular.module('myApp', ['ngSanitize']);
app.controller('personCtrl', function($scope,$http)
{
$scope.fun = function()
{
varible="<tr><td><strong>Id</strong></td><td><strong>ahmed</strong></td><td><strong>45kg</strong></td></tr>";
$scope.bind=varible;
};
});
这是我的 HTML 代码
<div ng-app="myApp" ng-controller="personCtrl">
<table ng-bind-html="bind">
</table>
<button ng-click="fun()">check</button>
</div>
最佳答案
您需要使用 $sce
将该字符串作为 html 信任,否则 Angular 不会使用它们,因为不安全:
app.controller('dummy', function($scope,$sce)
{
$scope.fun = function()
{
varible="<tr><td><strong>Id</strong></td><td><strong>ahmed</strong></td><td><strong>45kg</strong></td></tr>";
$scope.bind = $sce.trustAsHtml(varible);
};
});
最好使用指令,这是一个非常简单的例子:
HTML:
<div ng-app="app" ng-controller="dummy">
<table><custom-table ng-show="bind"></custom-table></table>
<button ng-click="bind=true">check</button>
</div>
JS:
app.directive('customTable',
function(){
return {
restrict: 'AE',
template: '<tr><td><strong>Id</strong></td><td><strong>ahmed</strong></td><td><strong>45kg</strong></td></tr>',
link: function(scope, element, attr) {
//If you need do something here
}
};
});
关于javascript - 无法更改表格的内部 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34199106/