3

I am building an application with Angular.js and Twitter Bootstrap.

HTML:

 <div ng-controller="myController"> 
 <label for="event">Event</label>
 <input type="text" ng-model="event"/>
 <label for="eventdate">Date</label>
 <div class="input-append date" id="datepicker" data-date-format="dd-mm-yyyy">
 <input class="span2" size="20" type="text" id="datepicker" ng-model="eventdate" required>
 <span class="add-on"><i class="icon-th"></i></span>
 <input class="btn-primary" type="submit" id="submit" value="Submit" ng-click="submit()" />
 </div>

Controller:

var myApp1 = angular.module('myApp1', []);
myApp1.controller('myController', function($scope) {
$('#datepicker').datepicker();
$scope.submit = function () {
console.log($scope.event);
console.log($scope.eventdate);
};
});

When I click "Submit" button,

console.log($scope.event); prints the data entered in event text box.

But console.log($scope.eventdate); prints "undefined" when I select a date from the date picker

What may be the reason?

Please advice.

user67867
  • 421
  • 4
  • 11
  • 24

1 Answers1

7

Your bootstrap datepicker is a 3rd-component outside of angular. When you change your date from the datepicker, angular is not aware of the changes.

You have to write a custom directive like this:

app.directive('datepicker', function() {
    return {

      restrict: 'A',
      // Always use along with an ng-model
      require: '?ngModel',

      link: function(scope, element, attrs, ngModel) {
        if (!ngModel) return;

        ngModel.$render = function() { //This will update the view with your model in case your model is changed by another code.
           element.datepicker('update', ngModel.$viewValue || '');
        };

        element.datepicker().on("changeDate",function(event){
            scope.$apply(function() {
               ngModel.$setViewValue(event.date);//This will update the model property bound to your ng-model whenever the datepicker's date changes.
            });
        });
      }
    };
});

Apply the directive to html:

<div class="input-append date" datepicker ng-model="eventdate" data-date-format="dd-mm-yyyy">
     <input class="span2" size="20" type="text" required="" />
     <span class="add-on">
        <i class="icon-th"></i>
     </span>
 </div>

DEMO

Khanh TO
  • 48,509
  • 13
  • 99
  • 115