2

When Json object comes from Server, date is always stored as string.

We need to show that date value in Input box to allow Edit/Update of object. But

<Input type="date>

only understands date object (rightly so), henceforth, we need to convert date string to date object, after receiving json from AJAX call. There are couple of threads on SO, trying to achieve same, but I found accepted answers on those thread not working (not even plunker).

Convert AJAX date to Javascript date for use with ng-model

angularjs | date input not showing ng-model value

  • I don't want to let go type="date" (don't want to loose dtPicker of mobile browsers).
  • I don't want to write a line everywhere on controller, converting a date string value to date. Though it does work, but I will keep it as last resort.

I tried to solve my problem using directive, and created following directive. I am trying to induce date object via ngModel.$formatters. Console.log inside jsonStrToDate prints str as empty string.

It is not working, What is wrong with my directive here?) :-

.html
   <input type="date" name="dateOfReading" class="form-control" id ="dateOfReading"
    ng-model="bpReport.dateOfReading"
    json-string-to-date
    min="1970-01-01" max="2099-12-31"  required />
.js
    window.angular.module('myApp.directives', [])
      .directive('jsonStringToDate', function(){
    return {
            restrict: 'A',
            require: 'ngModel',
            link: function(scope, element, attr, ngModel) {
              console.log('directive linking called');
              function jsonStrToDate(str) {
                console.log('input str value' + str + ', and typeof is ' + typeof str);
                var d= new Date(str);
                console.log(d);
                return d;
              }
              ngModel.$formatters.push(jsonStrToDate);
              ngModel.$parsers.push(function(value) {
                console.log("value from parser method:- "+ value);
                return value;
              });

            }
          };
        });

Right now I am using AngularJS 1.3.0 RC1 Version 1.2.20 also had same issue.

5
  • At what point do you have to convert the string to the object? Commented Sep 18, 2014 at 14:14
  • Can you provide plunker for your code Commented Sep 18, 2014 at 14:18
  • When I load the edit form, right after ajax call which loads the object from server. Commented Sep 18, 2014 at 18:09
  • plnkr.co/edit/KsPFMLMz7BOsEGoUwddW?p=preview Commented Sep 19, 2014 at 4:37
  • Thanks @HarishR If you can make, above plunkr to show date in fourth dropdown (which retrieve date from directive) , will solve my problem. Thanks. Commented Sep 19, 2014 at 5:05

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.