jqueryangularjsbootstrap-datepickerjquery-delegate

Angularjs+jquery bootstrap-datepicker delegate not firing on first click


I have tried adding the datepicker dynamically on button click and I have delegated the datepicker click which is not working on the first click its getting fired on the second click the code I have tried are the following

$scope.add = function()
    {
      var body =angular.element(window.document.body);
      body.append(`
        <div class="input-group date">
          <input class="form-control input-sm" 
                 placeholder="dd/mm/yyyy"type="text">
          <span class="input-group-addon">
            <span class="fa fa-calendar"></span>
          </span>
        </div>
      `);

    }

$(document).delegate("div.input-group.date", "click", function(){     
      $(this).datepicker({autoclose: true,orientation:"top"});       
});

I couldn't find out the reason, thanks in advance.

<html ng-app="app">
  <head>
    <link data-require="bootstrap@3.3.7" data-semver="3.3.7" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
    <script data-require="angular.js@1.5.3" data-semver="1.5.3" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js"></script>
    <script src="jquery-1.11.3.js"></script>
    <!-- Datepicker for Bootstrap v1.5.0 (https://github.com/eternicode/bootstrap-datepicker) -->
    <script src="datetimepicker.min.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body ng-controller="test">
      <input ng-click="add()" value="Add datepicker" type="button" />
  </body>

</html>

plnkr sample

steps to replicate bug:

  1. Click Add Datepicker button
  2. Date picker component will be added in DOM, then click in the datepicker

Observed

First click wont work, it will work from the subsequent clicks


Solution

  • Finally I found the reason and work around for the same. I am giving that solution since it may help to others in future

    Reason:

    First mistake is I have bind the datepicker event on element click so binding happened on the first click and it started working in subsequent clicks.

    Work around

    We have to bind the datepicker immediately after the element created I have solved this using the following code

    $scope.add = function()
        {
          var body =angular.element(window.document.body);
          var element=angular.element('<div class="input-group date">\
                          <input class="form-control input-sm"\
                          placeholder="dd/mm/yyyy" type="text">\
                          <span class="input-group-addon">\
                            <span class="fa fa-calendar"></span>\
                          </span>\
                      </div>');
          body.append(element);
          $(element).datepicker({autoclose: true,orientation:"top"});
    
        }