Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question
    
At what point do you have to convert the string to the object? –  Explosion Pills Sep 18 '14 at 14:14
    
Can you provide plunker for your code –  entre Sep 18 '14 at 14:18
    
When I load the edit form, right after ajax call which loads the object from server. –  Sutikshan Dubey Sep 18 '14 at 18:09
    
    
Thanks @HarishR If you can make, above plunkr to show date in fourth dropdown (which retrieve date from directive) , will solve my problem. Thanks. –  Sutikshan Dubey Sep 19 '14 at 5:05

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.