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

查看:161
本文介绍了DOM元素AngularJS指令的链接没有准备好()函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要创建一个应该有一个 C3.js 基于图表中的AngularJS指令它。问题是,C3库不看它应该附加到DOM元素。该指令的链接函数看起来是这样的:

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
}

有关指令的模板有这样的吧:

The template for the directive has this in it:

<div id="#somechart{{ scope.someid }}">...</div>

问题是, c3.generate()的 bindto 不看 #somechartid 。在的console.log()我已经把产出0,这意味着该元素是不是在目前的DOM present当链接函数被调用。

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.

如果我把从浏览器的控制台或者甚至在同一个图表生成code一些 NG-点击图表获取呈现。

If I call the same chart-generating code from the browser's console or even from some ng-click the chart gets rendered.

有没有办法解决这个问题,而无需使用类似 $超时的解决方案

Is there a way to overcome this problem without using a solution like $timeout?

更新2014年7月15日15:33 改变了code从指令的模板样本,并添加相关的行。

UPDATE 2014-07-15 15:33 Changed the code sample and added relevant line from directive's template.

推荐答案

在你的链接功能使用$超时功能,如果你想操作DOM,这还没有产生。请参见

Use $timeout function in your link function if you want to manipulate dom, which is not yet generated. See this

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

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