Arpit Meena Arpit Meena - 1 month ago 10
AngularJS Question

ui bootstrap datepicker not taking js Date() object as string

I am using ui bootstrap datepicker in my project, when i am getting data from database the type of this date value

Thu Aug 11 2016 00:00:00 GMT+0530 (India Standard Time)
is
string
when i am using

new Date('Thu Aug 11 2016 00:00:00 GMT+0530 (India Standard Time)');


Then it is working properly, i don't want to convert it in
controller
using
new Date();
, i actually want to achieve this conversion using
directive
or
filter
how can i achieve this? my datepicker field is:

<input type="text" class="form-control custom-form-control" uib-datepicker-popup="{{format}}" ng-model="moduleName.main.expiryDate" is-open="expiryDateCal.opened" datepicker-options="expiryDateOptions" name="expiryDate" ng-required="true" close-text="Close"/>

Answer

Using filter is not a good idea in the case of with ng-model.So instead I've created a directive which converts the string date to Date object.

Run the code sample to check the working.Hope this helps,you just need to add date attribute to the HTML tags with ng-model as required.

var app = angular.module('app',[]);
app.controller('Ctrl',function($scope,$filter){
  
  $scope.date="Thu Aug 11 2016 00:00:00 GMT+0530 (India Standard Time)";
   
  });

app.directive('date', function(dateFilter) {
  return {
    require: 'ngModel',
    
    link: function(scope, element, attrs, ngModelController) {
      ngModelController.$parsers.push(function(data) {
        //convert data from view format to model format
        return new Date(data); //converted
      });

      ngModelController.$formatters.push(function(data) {
        //convert data from model format to view format
        return new Date(data); //converted
      });
    }
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" class="widget-content" ng-controller="Ctrl">

  <input type="text" ng-model="date" date/>
  </div>

Comments