0

I currently have a problem with form validation and milliseconds. I guess time in milliseconds is not a valid date format in angular, as e.g. angular.isDate(1418645071000) is returning false.

But what to change in my code, so that the form validation is working? I do not have any restriction with the server - meaning a date in the format "Sat Feb 03 2001 00:00:00 GMT+0100 (CET)" is also being acceptable.

Here is the code: http://plnkr.co/edit/lZZh5VvCzH6yYh1t8xVM?p=preview

ilmgb
  • 770
  • 4
  • 20

2 Answers2

1

I found a solution based on this thread on stackoverflow https://stackoverflow.com/a/22658709/2012123

I filter the modelValue to my custom date format. So the viewValue will have the format 'dd.Mm.yy'.

ngModelCtrl.$formatters.push(function(modelValue) {
      if(modelValue) {
        var filtered = $filter('date')(modelValue, 'dd.MM.yy');
        return filtered;
      }
    });

And with the following code I immediately transform my milliseconds to a valid date

/*https://stackoverflow.com/questions/22639485/angularjs-how-to-change-the-value-of-ngmodel-in-custom-directive*/
    // $parse works out how to get the value.
    // This returns a function that returns the result of your ng-model expression.
    var modelGetter = $parse(attrs['ngModel']);
    console.log(modelGetter(scope));
    var timeInMilliseconds = modelGetter(scope);

    if(timeInMilliseconds != null) {
      // This returns a function that lets us set the value of the ng-model binding expression:
      var modelSetter = modelGetter.assign;

      // This is how you can use it to set the value 'bar' on the given scope.
      modelSetter(scope, new Date(timeInMilliseconds));
      console.log(modelGetter(scope));
    }

I have updated the http://plnkr.co/edit/lZZh5VvCzH6yYh1t8xVM?p=preview accordingly. Now there are no more validation errors.

Community
  • 1
  • 1
ilmgb
  • 770
  • 4
  • 20
0

angular.isDate checks if the argument provided is an object of date type.

You would first need to convert millinseconds to date using new Date(milliseconds)

harishr
  • 17,807
  • 9
  • 78
  • 125
  • Thanks. My fault - I did a wrong check. But how can I change my models value from 134786238467234 to a Date - I guess I need to do something with the ngModelCtrl. Any ideas? – ilmgb Jan 25 '15 at 17:55
  • `new Date(milliseconds)`, this does convert it to `Date object`, you need to do this in your controller – harishr Jan 25 '15 at 17:59
  • Ok. Did it - take a look into the plnkr, just added your proposal inside ModalInstanceCtrl in modal.js . But now the format doesn't look like the one I specified in the datepickers options. Any ideas on that? – ilmgb Jan 25 '15 at 18:07
  • I have updated the title of my question that it better reflects my current problem situation. Your answer is correct, but only was a part of the problem's solution. I have answered the question myself and accpeted it. Thanks – ilmgb Jan 27 '15 at 18:51