簡體   English   中英

日期選擇器格式不影響ng-model Angular Material

[英]Date-picker format not affecting ng-model Angular Material

我想在ng模型中使用DatePicker的這種格式['DD-MM-YYYY']格式。

我在config()中做到了

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

並在視圖和日志中返回有效的日期格式。

屏幕截圖

但這不會影響ng-model變量

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

因為當記錄此變量時,它會給我這種日期格式

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

ng-model的值是js Date對象。 使用服務來分類模型值:

var dateString = $mdDateLocale.formatDate(valueFromNgModel);

你去了!!!

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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM