I'm working on a directive that has the ability to use dynamic templates with expressions inside them.
The challenge I face is if I use ng-bind-html
, the expression won't be evaluated properly. On the other hand, using ng-bin-template
results in the HTML being returned as encoded text rather than actual HTML.
Is there a feature like ng-bind-html-template
available? Or do I need to create it myself?
Currently, my workaround involves using a function that allows developers to return the rendered HTML directly, but ideally, I would prefer to utilize a template.
UPDATE: When I mention "dynamic templates", I mean content that is user-defined and can contain unknown elements.
Here's an example of the code I'm working with:
// Columns definition in directive config provided by the user
columns: [
{
title: 'Measure Name',
name: 'measurename',
key: 'measurecode',
headerTemplate: function (content, col) {
return col.title + " <small><span class='label label-info'>Unit</span></small>";
},
template: function (item, content, col) {
return item.measurename + " <small><span class=\'label label-info\'>" + item.unitname + "</span></small>";
}
}
],
How the rendering process works:
$scope.renderHeaderCell = function (col) {
var content = col.title;
if (isFunction(col.headerTemplate)) {
var _content = col.headerTemplate(content, col);
if (angular.isDefined(_content) && _content !== false) {
content = _content;
} else if (angular.isDefined(col.headerTemplate)) {
content = col.headerTemplate;
return $sce.trustAsHtml(content);
};
}
}
How it should be used in the template:
<td ng-repeat="col in config.columns" width="200" ng-bind-html="renderHeaderCell(col)"></td>
However, I am aiming to pass the template directly to the config like this:
headerTemplate: "{{col.title}} <small><span class='label label-info'>Unit</span></small>",
and then utilize it in the template with something like:
<td ng-repeat="col in config.columns" width="200" ng-bind-html-template="col.headerTemplate"></td>