0
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:

enter image description here

1
  • use ng-bind-html="rTable" with ngSanitize module. Or compile it with $compile (in a directive) Commented Mar 14, 2018 at 15:10

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, But what I wanted to do is not possible like this, I needed a way that creates a table on run time.
Can you please explain the scenario why do you need to create table dynamically?
1

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.