我正在尝试使用一个库,该库接收表示html元素的字符串,并使用该字符串作为下拉列表的一部分动态呈现元素,但是该库假设您正在使用javascript来执行此操作。我试图用angular指令包装这个库,但我不确定如何使用$compile。我的问题如下。
我使用的库获取一个对象并使用它来确定如何渲染元素。建议的javascript实现是:
render: {
item: function(item) {
return '<div><span>' + item.firstName + '</span></div>';
}
然而,我想使用模板的内容,然后将其编译为一种使esk更具角度的方法。我有以下几点:
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呈现任何内容。有没有一种方法可以使$compile同步工作,或者有其他方法可以这样做,以便使用模板并将其转换为正确的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;
}
}