我正在尝试使用代表HTML元素的字符串的库,并使用该库将元素动态渲染为下拉列表的一部分,但是此库假定您是使用JavaScript这样做。我试图将此库包裹在Angular指令中,但我不确定如何使用$编译。我的问题如下。
我正在使用的库取一个对象并使用它来确定如何渲染元素。建议的JavaScript实现是:
render: {
item: function(item) {
return '<div><span>' + item.firstName + '</span></div>';
}
但是,我想使用模板的内容,然后对此进行编译,以使其更具角度。我有以下内容:
render: {
item: function(item) {
$scope.item = item;
var things = jQuery($templateCache.get('testingTemplate.modal.nested'));
var $el = $compile(things)($scope);
$timeout(() => {
return $el.prop('outerHTML');
}).then(function(working) {
return working;
});
console.log($el);
return $el;
}
我在此代码中遇到的显而易见的问题是,$ el的值是未定义的,因为这一点尚未完成,因此没有任何内容呈现给DOM。有没有一种方法可以同步进行$编译工作,或者我可以这样做,以便我可以使用模板并将其转换为适当的HTML表示?
已解决
我已经以以下方式解决了将来对此绊倒的任何人。请原谅命名不佳的变量。
render: {
item: function(item, escape) {
$scope.item = item;
var randomUnique = Math.random().toString(36).substring(7);
var things = jQuery("<div class='" + randomUnique + "'>" + $templateCache.get('testingTemplate.modal.nested') + "</div>");
var $compiledEl = $compile(things)($scope);
$timeout(() => {
var placeHolder = jQuery('.' + randomUnique);
placeHolder.replaceWith($compiledEl.prop('outerHTML'));
});
var hello = (things.prop('outerHTML'));
return hello;
}
}
找到了一个解决方案,尽管也许不是最好的,但它有效。请忽略命名不佳的变量。
render: {
item: function(item, escape) {
$scope.item = item;
var randomUnique = Math.random().toString(36).substring(7);
var things = jQuery("<div class='" + randomUnique + "'>" + $templateCache.get('testingTemplate.modal.nested') + "</div>");
var $compiledEl = $compile(things)($scope);
$timeout(() => {
var placeHolder = jQuery('.' + randomUnique);
placeHolder.replaceWith($compiledEl.prop('outerHTML'));
});
var hello = (things.prop('outerHTML'));
return hello;
}
}