I wrote an angular directive for http://eonasdan.github.io/bootstrap-datetimepicker, and I'm able to have actions on the datetimepicker update my model, but I'm running into problems when I'm trying to set the defaultDate on the datetimepicker control with the value from my model during instantiation.
Here's a plunker: http://plnkr.co/edit/XUQSx7s0Fle2Xes77VrM?p=preview
script.js
var app = angular.module('app', []);
app.controller('DemoCtrl', function($scope) {
$scope.modelDate = new Date("01/01/2010");
});
app.directive('datetimepicker', function() {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element, attrs, ngModelCtrl) {
// scope.$apply(); //This fixes the issue, but throws error in console
element.datetimepicker( {
defaultDate: ngModelCtrl.$modelValue
})
.on('dp.change', function(e) {
ngModelCtrl.$setViewValue(e.date);
scope.$apply();
});
}
};
});
Relevant portion of index.html
<div class="container">
<div class="form-group col-xs-6">
<div class="input-group date" datetimepicker ng-model="modelDate">
<input type="text" class="form-control" />
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
Date from model: {{modelDate}}
</div>
</div>
It looks like the problem is at the time datetimepicker gets instantiated, the model is null. Doing scope.$apply()
before instantiating the datetimepicker solves this problem, but throws an error in the console, and this doesn't feel like the right way to go about it. Any help would be appreciated!