DOM elements not ready in AngularJS Directive's link() function

自作多情 提交于 2020-01-03 10:54:39

问题


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>

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.

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?

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


回答1:


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




回答2:


Have you tried something like this

link: function(scope, element, attrs) {
    scope.chart = c3.generate({
        bindto: element[0],
        data: {
            columns: [
                ['data1', 30, 200, 100, 400, 150, 250],
                ['data2', 50, 20, 10, 40, 15, 25]
            ]
        }
    });         
}



回答3:


Maybe usage of element.find('#id') will help:

link: function(scope, element, attrs) {
    var item = element.find('#somechartid');
    scope.chart = c3.generate({
        bindto: item,
        data: {
            columns: [
                ['data1', 30, 200, 100, 400, 150, 250],
                ['data2', 50, 20, 10, 40, 15, 25]
            ]
        }
    });         
}


来源:https://stackoverflow.com/questions/24744311/dom-elements-not-ready-in-angularjs-directives-link-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!