Wait for angular to finish updating the DOM

2019-07-15 20:05发布

I need to attach bootstrap datepicker to one of my input fields that will be generated with AngularJS.

Doing the following doesn't work because the element does not yet exist:

$(function () {
    $(':input[name=dispense_date]').datepicker();
});

Instead I must do:

$(function () {
    setInterval(function () {
        $(':input[name=dispense_date]').datepicker();
    }, 200);
});

The latter version works but is inefficient and not exactly the "correct" way to do this. Do angular controllers/modules have a method for running callbacks after everything completes?

I need the jquery code to run after an $http.get() call, but simply adding it inside the .success() call won't do the trick since $apply hasn't ran yet.

1条回答
爷的心禁止访问
2楼-- · 2019-07-15 20:37

Use $timeout:

$timeout(function() {
    $(':input[name=dispense_date]').datepicker();
});

Angular will ensure that the timeout function executes after the compile/link phase and even after the render phase.

查看更多
登录 后发表回答