Introduction
In this article, we will learn how to implement Bootstrap DateTime picker as an Angular Directive in ASP.NET MVC.
Background
We can create Bootstrap DateTime Picker in MVC easily. Now, if we use it normally with ASP.NET MVC, we will face some problems and DateTime Picker won't work as expected. In order to avoid that, we need to do it in the Angular way. So, we will create it as a directive and we can use it wherever we want in our project.
Steps to be followed
Step 1. Create an application and download the below CSS and JS files to add Bootstrap DateTime Picker.
- bootstrap-datetimepicker.js
- moment.js
- angular.js
- bootstrap-datetimepicker.css
You can download it from NuGet Package Manager using the command Install-Package Bootstrap.datepicker -Version 1.6.4
Step 2. Refer to the above-shown files in the View page.
Step 3. Create the HTML markup to show the date and time in the textbox.
<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>
Step 4. Create one module in a JavaScript file or in the script tag.
var app = angular.module("Myapp", []);
Create one directive named dateTimePicker and add it to the app module.
app.directive("dateTimePicker", DatetimePicker);
Create one function for the dateTimePicker directive and add the following code.
function DatetimePicker() {
return {
restrict: "A",
require: "ngModel",
link: function (scope, element, attrs, ngModelCtrl) {
var parent = $(element).parent();
var dtp = parent.datetimepicker({
format: "DD-MM-YYYY hh:mm",
showTodayButton: true
// pickTime: true
});
dtp.on("dp.change", function (e) {
ngModelCtrl.$setViewValue(moment(e.date).format("DD-MM-YYYY hh:mm"));
scope.$apply();
});
}
};
}
In the above code, we are restricting the dateTimePicker directive to "Attribute only" and we will be using some “ngModel” for getting and setting the value of the selected date time. Inside the link function, we are manipulating the DOM and adding some bootstrap datetimepicker values to it. Also, we are adding datetimepicker change event in order to set the values to ngmodel.
Step 5. Create a Controller in a script in order to bind the values to the Model and show it in View.
app.controller("ctrl", function ($scope) {
$scope.test = "Angular Js Date time picker";
$scope.selectedDt = "";
$scope.showDate = function () { // function to show date as alert
alert($scope.selectedDt);
}
});
And, add this directive as an attribute to HTML markup.
<input type='text' class="form-control" ng-model="selectedDt" data-date-time-picker />
Add a click event to HTML in order to show the selected date.
<button class="btn btn-success" ng-click="showDate()">
Display selectedTime
</button>
Now, save it and run it. You will find the below output. You can reuse the same directive multiple times.