Reputation: 39
var str1 = "Sarah";
var str2 = "Tom";
var strTable = "<table style='width:100%'><tr><th>"+ str1 +"</th><th>"+ str2 +"</th> <th>Age</th> </tr> <tr> <td>Jill</td><td>Smith</td><td>50</td></tr></table>";
$scope.rTable= strTable;
I am trying to pass HTML code in $Scope.rTable
but instead of rendering the table it shows the HTML code as it is in the output.
i.e.
<table style='width:100%'><tr><th>Sarah</th><th>Tom</th> <th>Age</th> </tr> <tr> <td>Jill</td><td>Smith</td><td>50</td></tr></table>
I want it like:
Upvotes: 0
Views: 1879
Reputation: 1325
Use ng-bind-html and $sce.
Controller
app.controller('MainCtrl', function($scope, $sce) {
var str1 = "Sarah";
var str2 = "Tom";
var strTable = "<table style='width:100%'><tr><th>" + str1 + "</th><th>" + str2 + "</th> <th>Age</th> </tr> <tr> <td>Jill</td><td>Smith</td><td>50</td></tr></table>";
$scope.rTable = $sce.trustAsHtml(strTable);
});
HTML
<body ng-controller="MainCtrl">
<div ng-bind-html="rTable"></div>
</body>
Upvotes: 1
Reputation: 511
Its a improper way to code. The code should be like
In Controller
$scope.str1 = "Sarah";
$scope.str2 = "Tom";
In HTML
Considering your controller name as DemoController
<body ng-controller="DemoController">
<table style='width:100%'>
<tr><th> {{str1}} </th>
<th> {{str2}} </th>
<th>Age</th>
</tr>
</table>
</body>
And if your data is huge its recommended to use an Array of Object with ng-repeat. you can read it here -> https://docs.angularjs.org/api/ng/directive/ngRepeat
Upvotes: 3