I'm using Angular 1.4.8. I'm trying to dynamically generate a table where the contents of the cells will be injected from variables in my controller.
I've used the $compile
service to do something similar when making a directive, but $compile
doesn't seem to work here.
Here's a simplified version of what I'm trying to do:
html
<div ng-controller="SimpleController">
<div ng-bind-html="tableHtml"></div>
</div>
factory.js
var table = {
title: "table title"
};
factory.buildHtml = function() {
return "<div>{{ table.title }}</div>";
}
factory.getTable = function() {
return table;
};
controller.js
$scope.table = SimpleFactory.getTable();
$scope.tableHtml = $sce.trustAsHtml(SimpleFactory.buildHtml());
// also tried:
// $scope.tableHtml = $compile($sce.trustAsHtml(SimpleFactory.buildHtml()))($scope);
// and:
// $scope.tableHtml = $sce.trustAsHtml($compile(SimpleFactory.buildHtml())($scope));
The html just outputs the text {{table.title}}
, which is predictable, but I want it to link to the scope to pull the title
property from my $scope.table
variable (i.e. I want it to write "table title"). Any suggestions?
Edit
I created a plunkr to demonstrate my problem.
In addition to my original code, I added some code from the solution to this question to my plunkr to demonstrate that it doesn't work how I want it to work. I believe it is a distinct problem: since the code is coming from a variable in my factory, the custom directive isn't recognized because the variable text (e.g. "<div>{{ table.title }}</div>"
or "<div dynamic='table.title'></div>"
) isn't being compiled before its inserted into my page.
There is probably a way to make a directive that solves my problem, but that is the purpose of this question because I don't know how to do that.
Edit #2
It turns out that this was in fact a duplicate of this question, though I didn't understand it at the time.
The solution is to add the directive outlined in the answer to the above question, then display the data with <div dyanmic="tableHtml"></div>
instead of using ng-bind-html
. So the correct, working HTML page is below:
html
<div ng-controller="SimpleController">
<div dyanmic="tableHtml"></div>
</div>
These edits are also saved in the plunkr that I made.