dhalia
dhalia

Reputation: 421

AngularJS binding datatimepicker selected value to ng-model

I have a newbie AngularJS question - I am using a datetimepicker library and I'm having a hard time getting the date selected to bind to my model... I saw some posts talking about not being able to access the datetimepicker model directly, but in my case I find that if I just manually TYPE IN a text value in my date input box, it binds! If I select a date with the chooser, I get the dreaded 'undefined' :(... help?

HTML markup:

<div class="col-md-2">
  <div name="fromDateTime" class="input-group date" id="datetimepickerFrom">
    <input class="form-control" type="text" name="fromDateTime" ng-model="formEntries.fromDateTime"/>
      <span class="input-group-addon" data-ng-click="pickFromDateTime()"><span class="glyphicon glyphicon-calendar" id="calIconFrom"></span></span> 
  </div>
</div>

<div class="col-md-2">
  <div name="toDateTime" class="input-group date" id="datetimepickerTo">          
    <input class="form-control" type="text" name="toDateTime" ng-model="formEntries.toDateTime"/>
      <span class="input-group-addon" data-ng-click="pickToDateTime()"><span class="glyphicon glyphicon-calendar"></span></span>
 </div>
</div>

Controller:

$scope.pickFromDateTime = function () {
   $("#datetimepickerFrom").datetimepicker();
   $("#datetimepickerFrom").datetimepicker().change(function() {       
       $(this).data("DateTimePicker").hide();
       console.log($(this).data("DateTimePicker").getDate()); 
   });
}


$scope.pickToDateTime = function () {
   $("#datetimepickerTo").datetimepicker();
   $("#datetimepickerTo").datetimepicker().change(function() {
       $(this).data("DateTimePicker").hide();
       console.log($(this).data("DateTimePicker").getDate());   
   });
}

$scope.getData = function() {
    console.log($scope.formEntries.fromDateTime);
    console.log($scope.formEntries.toDateTime);

}

Upvotes: 0

Views: 1014

Answers (1)

Jonathan Rowny
Jonathan Rowny

Reputation: 7588

Never ever ever write DOM or jQuery code in your controller. It will never work properly. You must create a directive to do this. The directive will listen to events from whatever library you're using and update your model. Here is an example of a directive that happens to work with the datepicker. This should get you on the right track.

Upvotes: 1

Related Questions