0

I have implemented checkin - checkout dates (like checkin - 10/03/2016 checkout - 12/03/2016) with JQuery datepicker. But now I want the same functionality using AngularJS.

My code is as below:

    $("#checkin_date").datepicker({
        dateFormat: "dd/mm/yy",
        minDate:  0,
        onClose: function(date){            
            var date1 = $('#checkin_date').datepicker('getDate');           
            var date = new Date( Date.parse( date1 ) ); 
            date.setDate( date.getDate() + 1 );        
            var newDate = date.toDateString(); 
            newDate = new Date( Date.parse( newDate ) );   
            $('#checkout_date').datepicker("option","minDate",newDate);            
        }
    });
    $('#checkout_date').datepicker({
        dateFormat: "dd/mm/yy" 
    });

I implemented it partially

<form name="form" ng-controller="ro" ng-submit="form.$valid && ge()">
   <input type="text" class="date" jqdatepicker ng-model="checkin" name="checkin" Placeholder="Check-In date" ng-required="true"  />
   <input type="text" class="date" jqdatepicker ng-model="checkout" name="checkout" Placeholder="Check-Out date" ng-required="true" />

Angular code:

var app = angular.module('App', []);
app.directive('jqdatepicker', function () {
return {
    restrict: 'A',
    require: 'ngModel',
    link: function (scope, element, attrs, ngModelCtrl) {
        element.datepicker({
            dateFormat: 'dd/mm/yy',
            onSelect: function (date) {
                scope.checkin = date;
                scope.$apply();
            }
        });
        /* where to add 2nd datepicker*/
    }
};
});

Any help or suggestions.

Vilas
  • 837
  • 2
  • 15
  • 41

1 Answers1

1

I am suggesting you to create directive(component) with 2 datepickers which will cover daterange cases where needed, in your example it will be check in - check out. So the directive will control 2 datepicker instances in link function as it was in you jquery code.

I have created JSBin with example https://jsbin.com/nenixo/23/edit?html,js,output.

I created directive with template, template can be placed in separate file and referenced via relative url in templateUrl param.

Also I used $timeout instead of scope.$apply since every time on $timeout execute, angular will trigger digest and all bindings will be updated. It's more safely then direct call of apply method because it can interrupt already executing digest.

Sergiy Kozachenko
  • 1,399
  • 11
  • 31