Making Bootstrap DateTimePicker work with AngularJs

There are a number of date time pickers which works with AngularJs and Bootstrap, but the best I found so far is Bootstrap 3 Datepicker Bootstrap 3 DateTimePicker.

The only issue with this DateTimePicker it 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)

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

Now let's create 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();
                    });
                }
            };
        };

bootstrap datetimepicker with angularjs

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

After we have our directive ready, we can apply it on 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 button with 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 are in GitHub repository, you need to look into Views/Home/Index.cshtml, all javascript and html are in that single file.



Comments

Social media

Search

Latest Tweets