简体   繁体   中英

ionic input date set default to today

I'm working on an Ionic application. I'm trying to set a default date (today) on an input date.

My code works if the type of input is text . But it doesn't work if I define an date type .

HTML code :

<html ng-app="ionicApp">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">

  <title>Date with Ionic</title>

  <link href="//code.ionicframework.com/nightly/css/ionic.css" rel="stylesheet">

  <script src="//code.ionicframework.com/nightly/js/ionic.bundle.js"></script>

</head>

<body ng-controller="GraphCtrl">

  <ion-header-bar class="bar-positive">
    <h1 class="title">Ionic Date</h1>
  </ion-header-bar>

  <ion-content>
    Text : <input type="text" ng-model="date_rdv" />
    Date : <input type="date" ng-model="date_rdv" />
  </ion-content>

</body>
</html>

My JS code :

angular.module('ionicApp', ['ionic'])

.controller('GraphCtrl', function($scope, $filter) {
  $scope.date_rdv = $filter('date')(Date.now(), 'yyyy-MM-dd');
});

Do you have any idea ?

Codepen.io link

Solution (according to Elec's answer)

In order to define a defaultvalue on date input (not functionnal with text input), the definition of model must be as following :

$scope.date_rdv = new Date();

you should use new Date() instead. you don't need to filter.

The model must always be a Date object, otherwise Angular will throw an error. Invalid Date objects (dates whose getTime() is NaN) will be rendered as an empty string.

AngularJs documentation for input[data]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM