AngularJS 指令的 link() 函数中的 DOM 元素未准备好
我正在创建一个 AngularJS 指令,它应该有一个基于 C3.js 的图表它.问题是 C3 库没有看到它应该附加到的 DOM 元素.指令的 link
函数看起来像这样:
I'm creating a AngularJS directive that is supposed to have a C3.js-based chart in it. Problem is that the C3 library does not see the DOM element it's supposed to attach to. The directive's link
function looks something like this:
link: function(scope, element, attrs) {
scope.someid = 'id';
scope.chart = c3.generate({
bindto: "#somechart"+scope.someid,
data: {
columns: [
['data1', 30, 200, 100, 400, 150, 250],
['data2', 50, 20, 10, 40, 15, 25]
]
}
});
console.log($("#somechart"+scope.someid).size()); // this is a test, outputs 0
}
指令的模板中有这个:
<div id="#somechart{{ scope.someid }}">...</div>
问题在于c3.generate()
的bindto
没有看到#somechartid
.console.log()
我已经输入了输出 0,这意味着在调用 link
函数时元素不存在于 DOM 中.
The problem is that the c3.generate()
's bindto
does not see the #somechartid
. The console.log()
I've put in outputs 0 which means the element is not present in the DOM at the moment when the link
function is called.
如果我从浏览器的控制台或什至从某些 ng-click
调用相同的图表生成代码,图表就会被渲染.
If I call the same chart-generating code from the browser's console or even from some ng-click
the chart gets rendered.
有没有办法在不使用像 $timeout
这样的解决方案的情况下克服这个问题?
Is there a way to overcome this problem without using a solution like $timeout
?
UPDATE 2014-07-15 15:33 更改了代码示例并添加了指令模板中的相关行.
UPDATE 2014-07-15 15:33 Changed the code sample and added relevant line from directive's template.
如果要操作尚未生成的 dom,请在链接函数中使用 $timeout 函数.请参阅这个
Use $timeout function in your link function if you want to manipulate dom, which is not yet generated. See this