5

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.

TheOne
  • 10,819
  • 20
  • 81
  • 119

1 Answers1

8

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.

Michael Kang
  • 52,003
  • 16
  • 103
  • 135
  • pixelbits, Is there a version of $timeout that runs after $http.success() has ran? – TheOne Jul 16 '14 at 23:00
  • @ramin - no I'm pretty sure there is not. That being said, $timeout returns a promise so you can easily chain the $timeout to run after your $http call (which also returns a promise) – Michael Kang Jul 16 '14 at 23:01
  • 1
    You can put the $timeout call within the success handler - it may trigger another digest but that is core to the way angular works. You probably don't need two chained promises - you'll manipulate models in your success handler, then you might want to call $timeout in the success handler to re initialize your datepicker – Michael Kang Jul 16 '14 at 23:15
  • Suppose I change a data (which is bind in the view). Is it possible to wait for angular to render and then do something? – Mostafa Barmshory Jun 01 '17 at 09:05