Richard Bailey Richard Bailey - 2 months ago 19
Javascript Question

bootstrap-datepicker (range) - Angular Directive

I'm trying to make use of the bootstrap-datepicker.
I have an existing angular directive, but when setting the initial value, it does not update when making use of a date range.

HTML



<div class="input-group input-daterange" id="fromToDate" calendar ng-model="vm.fromToDate">
<input type="text" class="form-control input-sm" required ng-model="vm.bookingFromDate">
<span class="input-group-addon">to</span>
<input type="text" class="form-control input-sm" required ng-model="vm.bookingToDate">
</div>


Directive



// this directive updates the value, once it has been selected, but not when the initial value has been set**
function calendar() {
return {
require: 'ngModel',
link: function($scope, el, attr, ngModel) {
$(el)
.datepicker({
autoclose: true,
todayHighlight: true,
todayBtn: 'linked',
onSelect: function(dateText) {
$scope.$apply(function() {
ngModel.$setViewValue(dateText);
});
}
});
}
};
};


Then, I tried the following directive (found here), but this doesn't work either for a date range - instead:

function calendar() {
return {
require: '?ngModel',
restrict: 'A',
link: function ($scope, element, attrs, controller) {
var updateModel, onblur;

if (controller != null) {

updateModel = function (event) {
element.datepicker('hide');
element.blur();
};

onblur = function () {
var date = element.val();
return $scope.$apply(function () {
return controller.$setViewValue(date);
});
};

controller.$render = function() {
var date = controller.$viewValue;
element.datepicker().data().datepicker.date = date.from.toDate();
element.datepicker('setValue');
element.datepicker('update');
return controller.$viewValue;
};
}
return attrs.$observe('bdatepicker', function (value) {
var options = {
format: "yyyy/mm/dd",
todayBtn: "linked",
autoclose: true,
todayHighlight: true
};
return element.datepicker(options).on('changeDate', updateModel).on('blur', onblur);
});
}
};
};


Any assistance would be appreciated!
Thanks!

[Update]

CodePen to illustrate the issue:



<p data-height="322" data-theme-id="dark" data-slug-hash="BLkagb" data-default-tab="js,result" data-user="Programm3r" data-embed-version="2" class="codepen">See the Pen <a href="http://codepen.io/Programm3r/pen/BLkagb">Bootstrap-Datepicker (Range) AngularJS</a> by Richard (<a href="http://codepen.io/Programm3r">@Programm3r</a>) on <a href="http://codepen.io">CodePen</a>.</p>
<script async src="//assets.codepen.io/assets/embed/ei.js"></script>




Answer

Use the following library to solve the issue. datepicker

Edit: to resolve disappearance of date.

<input type="text" class="form-control input-sm" ng-model="vm.bookingFromDate" id="fromDate">
<span class="input-group-addon">to  </span>
<input type="text" class="form-control input-sm" ng-model="vm.bookingToDate" id="toDate">

//in controller

$('#fromDate').val(vm.bookingFromDate);
$('#toDate').val(vm.bookingToDate);
Comments