Amr Ibrahim
Amr Ibrahim

Reputation: 2234

Date-picker format not affecting ng-model Angular Material

I Want this format [ 'DD-MM-YYYY' ] form DatePicker, in my ng-model.

i did this in config()

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

and it return valid date format in view and log.

screenshot

but this not affecting the ng-model variable

 <md-datepicker ng-model="user.bod" md-placeholder="Enter birth date "> </md-datepicker>

because when if log this variable it give me this date format

Mon May 30 2016 00:00:00 GMT+0200 (EET)

Upvotes: 0

Views: 823

Answers (2)

Beqa
Beqa

Reputation: 99

THERE YOU GO!!!

https://stackoverflow.com/a/43392704/5613548

angular.module('MyApp')

.controller('AppCtrl', function($scope) {
  $scope.person = {
    name: "John",
    birthDate: "1990-01-01 00:00:00"
  };
})

.directive('mdDatepicker', function () {
  function link(scope, element, attrs, ngModel) {
    var parser = function (val) {
      val = moment(val).format('YYYY-MM-DD hh:mm:ss');
      return val;
    };
    var formatter = function (val) {
      if (!val) return val;
      val = moment(val).toDate();
      return val;
    };
    ngModel.$parsers.push(parser);
    ngModel.$formatters.push(formatter);
  }
  return {
    require: 'ngModel',
    link: link,
    restrict: 'EA',
    priority: 1
  }
});
<link href="https://material.angularjs.org/HEAD/docs.css" rel="stylesheet"/>
<link href="https://material.angularjs.org/HEAD/angular-material.css" rel="stylesheet"/>


<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular-animate.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular-aria.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular-messages.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular-route.min.js"></script>
<script src="https://material.angularjs.org/HEAD/angular-material.js"></script>
<script src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/t-114/assets-cache.js"></script>



<div ng-app="MyApp" ng-controller="AppCtrl">
  <md-content>
    <md-datepicker ng-model="person.birthDate" md-placeholder="Enter date"></md-datepicker>
  </md-content>
  
  <big>ng-model value is: <strong>{{person.birthDate}}</strong></big>
</div>

Upvotes: 1

Valery Kozlov
Valery Kozlov

Reputation: 1577

ng-model value is js Date object. use service to stringify model value:

var dateString = $mdDateLocale.formatDate(valueFromNgModel);

Upvotes: 1

Related Questions