1

I got a input field type date. There is date picker by AngularJS. When user comes to edit already saved form, AngularJS is throwing an error and date is not set at all, it is empty in UI. I really appreciate for your help!

HTML

<div class="col-md-10">
        <input type="date" name="purchaseDate"  class="form-control"  ng-model="rma.purchaseDate" placeholder="{{translation.DATEOFPERMIT_PLACEHOLDER}}">
</div>

Controller

//In mySQL DB format is: 2015-07-02
$scope.rma.purchaseDate = $filter("date")(new Date(rma.purchaseDate).toISOString(), 'dd-MM-yyyy');
console.log($scope.rma.purchaseDate);

in console.log

Error: [ngModel:datefmt] Expected 02-07-2015 to be a date

The specified value '02-07-2015' does not conform to the required format, 'yyyy-MM-dd'.

In UI

In the UI the format is dd/mm/yyyy

UPDATE

I just took filter off and tried very simple way and this is working:

 $scope.rma.purchaseDate = new Date(rma.purchaseDate);

Thanks all!

Community
  • 1
  • 1
Sami
  • 2,311
  • 13
  • 46
  • 80
  • exactly which datepicker are you using? link? – J-Dizzle Jul 12 '15 at 15:28
  • what's the format to be shown on UI? which datepicker? – Sudhansu Choudhary Jul 12 '15 at 15:32
  • 1
    as far as I know angular 1.3+'s ngModel with type="date" need date to be real date object (angular 1.2 was not) and HTML5 expect it as String. So you need ngModel $formatters like http://stackoverflow.com/questions/14474555/how-to-format-a-date-using-ng-model – YOU Jul 12 '15 at 15:34
  • @Sudhansu Choudhary - Like I said in my q: In the UI the format is dd/mm/yyyy. I use the AngularJS default datepicker, it is working only in chrome. – Sami Jul 12 '15 at 15:34
  • @YOU - Thanks for your link. There was a one comment and I tried it and this works: $scope.rma.purchaseDate = new Date(rma.purchaseDate); – Sami Jul 12 '15 at 15:41
  • So, actually, @ghost's deleted answer was correct for you. you just didn't need .toISOString() on angular 1.3+ – YOU Jul 12 '15 at 15:42

1 Answers1

0

you need to provide a valid javascript object to ng-model of date input,

here is the DOC

it says,

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.

to do that you can create a javascript date like,

//In mySQL DB format is: 2015-07-02
var dateVal = '2015-07-02';
var datePartials = dateVal.split("-");
var dateModel = new Date(datePartials[0], datePartials[1] - 1, datePartials[2]);

$scope.rma.purchaseDate = dateModel;

here is a DEMO

Kalhan.Toress
  • 21,683
  • 8
  • 68
  • 92