0

I found a jquery-ui angular date picker directive to use. It works fine except the format when it is populated with a date from the db. right now it shows 2014-08-10T00:00:00. I need the mm-dd-yy format. also when I open the datepicker the default value is todays date, I need it to show up on the date from the db. I cannot use angular-ui datepicker because of the design and look. thanks plunkr

app.directive("datepicker1", function () {
    return {
        restrict: "A",
        require: "ngModel",
        link: function (scope, elem, attrs, ngModelCtrl) {
            var updateModel = function (dateText) {
                // call $apply to bring stuff to angular model
                scope.$apply(function () {
                    ngModelCtrl.$setViewValue(dateText);
                });
            };

            var options = {
                dateFormat: "dd-mm-yy",
                // handle jquery date change
                onSelect: function (dateText) {
                    updateModel(dateText);
                }
            };

            // jqueryfy the element
            elem.datepicker(options);
        }
    }
});

 <input type="text" style="width:150px" ng-model="currentItem.ChangeOrderDate" datepicker1 />
texas697
  • 5,609
  • 16
  • 65
  • 131

1 Answers1

1

If you need to use jQuery (and not angular-ui, which I too recommend), you have to take several steps:

  1. Implement the ngModelCtrl.$render function. It needs to transform the model to a user presentable value. This is easy using $.datepicker.formatDate() (ref):

    ngModelCtrl.$render = function() {
        var d = new Date(ngModelCtrl.$viewValue), txt;
        if( isNaN(d.getTime()) ) {
            txt = "";
        }
        else {
            txt = $.datepicker.formatDate("dd-mm-yy", d);
        }
        elem.val(txt);
    };
    

    Details on this here - check "custom controls"

  2. The presentation, i.e. the <h1>Selected date: {{date}}</h1> part, has to use a display filter for the date. Luckily Angular provides us with the date filter:

    <h1>Selected date: {{date | date:'dd-MM-yyyy' }}</h1>
    
  3. I would also suggest storing a date object in the controller, so:

    $scope.date = new Date('2014-08-10T00:00:00');
    

    and:

    var updateModel = function (dateText) {
        // call $apply to bring stuff to angular model
        scope.$apply(function () {
            ngModelCtrl.$setViewValue($.datepicker.parseDate(FORMAT, dateText));
        });
    };
    

A working plunker implementing this: http://plnkr.co/edit/J1acskcSh4xXI3kan32W

Nikos Paraskevopoulos
  • 39,514
  • 12
  • 85
  • 90