Kamlesh Pawar
Kamlesh Pawar

Reputation: 45

angular material date picker field value empty

I want to get date of birth of a user, with predefined min and max date which is working fine. And the date format i want is DD-MM-YYYY, for this i have defined following in config;

app.config(['$mdDateLocaleProvider', function ($mdDateLocaleProvider) {
      $mdDateLocaleProvider.formatDate = function(date) {
         return moment(date).format('DD-MM-YYYY');
      }}]);

and the controller has

    $scope.user = {};
    $scope.user.dob = new Date();
    $scope.maxDate = new Date(
       $scope.user.dob.getFullYear() - 10,
       $scope.user.dob.getMonth(),
       $scope.user.dob.getDate()
    );
    $scope.minDate = new Date(
       $scope.user.dob.getFullYear() - 120,
       $scope.user.dob.getMonth(),
       $scope.user.dob.getDate()
    );

and the HTML is;

<md-datepicker 
 ng-model="user.dob" 
 md-placeholder="Enter date of birth"
 md-min-date="minDate" 
 md-max-date="maxDate">
</md-datepicker>

with this code the field shows current date by default, which i don't want,

i want the date field to be empty by default.

Also i want to get values in both ways as follows 1) date-month-year And 2) date-month-year hour-minutes-seconds

When i tried to get the value it shows this "09-11-2016T18:30:00.000Z"

i want either "09-11-2016" or "09-11-2016 18:30:00"

Upvotes: 3

Views: 10716

Answers (2)

Martin Eckleben
Martin Eckleben

Reputation: 802

Your mdDateLocaleProvider doesnt check for null values.

Your Problem is:

app.config(['$mdDateLocaleProvider', function ($mdDateLocaleProvider) {
  $mdDateLocaleProvider.formatDate = function(date) {
     return moment(date).format('DD-MM-YYYY');
  }}]);

it needs to be something like:

$mdDateLocaleProvider.formatDate = function(date) {
   var m = moment(date);
   return m.isValid()? m.format('DD-MM-YYYY') : '';
};

Then you can set

$scope.user.dob=null;

And get an empty Datepicker.

Upvotes: 5

Luca Argenziano
Luca Argenziano

Reputation: 144

The problem is your ng-model. You're initializing it with the current date:

$scope.user.dob = new Date();

Simply empty this variable and you'll be good ;)

Upvotes: 0

Related Questions