Select Page

There are a number of DateTime pickers that work with AngularJs and Bootstrap, but the best I have found so far is Bootstrap 3 Datepicker Bootstrap 3 DateTimePicker.

The only issue with this DateTimePicker does not work with AngularJs out of the box, but it’s not a big issue and can be easily fixed with a simple AngularJs directive.

There are some prerequisites. You need to attach the following libraries in order to have DateTimePicker work (in this case it is Nuget packages):

  • Bootstrap.v3.Datetimepicker.CSS
  • Moment.js
  • AngularJS.Core
  • bootstrap (preinstalled with asp.net MVC)

Source code

If you just want to get a working copy of the solution, you can find it in the following GitHub repository.

Now let’s create an AngularJS directive, which we can apply to our input control in order to make it behave like DateTimePicker.


var dateTimePicker = function() {
  return {
    restrict: "A",
    require: "ngModel",
    link: function(scope, element, attrs, ngModelCtrl) {
      var parent = $(element).parent();
      var dtp = parent.datetimepicker({ format: "LL", showTodayButton: true });
      dtp.on("dp.change", function(e) {
        ngModelCtrl.$setViewValue(moment(e.date).format("LL"));
        scope.$apply();
      });
    }
  };
};

So what exactly that AngularJS directive does? First, it trying to find the parent of the input element, which is div and creates DateTimePicker on that div, it is done to show calendar on both clicks on calendar icon and textbox. Second, it notifies the controller that the value of the model changed when we select a new date db.change event. And the last one, formats date to the desired format, in my case LL produce date like September 1, 2015

After we have our directive ready, we can apply it to the input tag this way


<div class="form-group">
    <div class='input-group date' id='datetimepicker1'> 
        <input type='text' class="form-control" ng-model="selectedDt"
            data-date-time-picker /> 
                <span class="input-group-addon"> 
                    <span class="glyphicon glyphicon-calendar"></span>
        </span> 
    </div>
</div>    

To validate how it works, I can have a button with an event showing selected date and time or just write in on the page like this:


    <div class="col-sm-2">  
        <button ng-click="submit()">
            Display selectedTime
        </button> 
    </div> 
    <div>  {{selectedDt}} </div>

The working ASP.NET MVC solution is in the GitHub repository, you need to look into Views/Home/Index.cshtml, all javascript and HTML are in that single file.