AngularJS 指令的 link() 函数中的 DOM 元素未准备好 [英] DOM elements not ready in AngularJS Directive's link() function

查看:38
本文介绍了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

这篇关于AngularJS 指令的 link() 函数中的 DOM 元素未准备好的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆