I am getting a date time value from asp.net mvc controller as \"2014-08-31T00:00:00Z\". When I bind this value to my angular-ui datepicker control it\'s state is showing as ng-i
To use formatted date string instead of Date object as ng-model for Angular Datepicker, you need to create a wrapper directive. The wrapper directive will parse your string into Date object and pass it to the datepicker. When you select a date, it is converted from Date back into string. Here is an example (Plunker):
(function () {
'use strict';
angular
.module('myExample', ['ngAnimate', 'ngSanitize', 'ui.bootstrap'])
.controller('MyController', MyController)
.directive('myDatepicker', myDatepickerDirective);
MyController.$inject = ['$scope'];
function MyController ($scope) {
$scope.dateFormat = 'dd MMMM yyyy';
$scope.myDate = '30 Jun 2017';
}
myDatepickerDirective.$inject = ['uibDateParser', '$filter'];
function myDatepickerDirective (uibDateParser, $filter) {
return {
restrict: 'E',
scope: {
name: '@',
dateFormat: '@',
ngModel: '='
},
required: 'ngModel',
link: function (scope) {
var isString = angular.isString(scope.ngModel) && scope.dateFormat;
if (isString) {
scope.internalModel = uibDateParser.parse(scope.ngModel, scope.dateFormat);
} else {
scope.internalModel = scope.ngModel;
}
scope.open = function (event) {
event.preventDefault();
event.stopPropagation();
scope.isOpen = true;
};
scope.change = function () {
if (isString) {
scope.ngModel = $filter('date')(scope.internalModel, scope.dateFormat);
} else {
scope.ngModel = scope.internalModel;
}
};
},
template: [
'',
'',
'',
'',
'',
''
].join('')
}
}
})();
Date format: {{dateFormat}}
Value: {{myDate}}