1

I'm new to Angular and to JS, therefore I'm sorry if my problem is quite trivial.

I'm using ui.bootstrap.datepicker to modify a date property of my foo model. My foo.date is a string like '2000-01-31'. What I want is to visualize foo.date in the form as January 31, 2000, while preserving 'foo.date' format to '2000-01-31'.

Here there is my datepiker:

<div class="input-group">
    <input type="text"
    class="form-control"
    datepicker-popup="MMMM dd, yyyy"
    ng-model="foo.date"
    is-open="opened"
    ng-required="true"
    show-weeks = 'false'
    close-text="Close" />
    <span class="input-group-btn">
        <button type="button" class="btn btn-default" ng-click="pdfc.open($event)"><i class="glyphicon glyphicon-calendar"></i></button>
    </span>
</div>

If I set datepicker-popup to "MMMM dd, yyyy", the original date format of the model is broken. I see something like this:

"2000-01-31T00:00:00.000Z"

...instead of this:

2000-01-31

I read some related solutions like this one, but the directive.directive('datepickerPopup', function (){...} is "overridden" by datepicker-popup in the form.

In this plnkr you can see my problem in action. Is there a nice way to decouple those two date formats?

Community
  • 1
  • 1
floatingpurr
  • 7,749
  • 9
  • 46
  • 106

1 Answers1

1

Use date filter. Here is what it can do. First inject filter service to your controller:

.controller('myCtrl',['$filter','$scope',function($filter,$scope){//..}]);

If you have other services to inject, read about dependency injection.

Second, assign new variable with date filter.

var dateView = $filter('date')($scope.foo.date,'MMMM d, yyyy');

Then you can show it: (Controller)

$scope.foo.fDate = dateView;

(View)

{{foo.fDate}}

To observe it after change, set watch on it:

$scope.$watch(function() { return $scope.foo.date; },
function(n,o){
 var dateView = $filter('date')($scope.foo.date,'MMMM d, yyyy');
 $scope.foo.fDate = dateView;
});

It will listen for changes and change it. It is better to show it in another variable. Of course you can set in watch instead of fDate, foo.date, but you may help problem with manual editing label, because variable will be changed after one letter is written.

changtung
  • 1,614
  • 15
  • 19
  • Oh...perfect! I made this new [plnkr](http://plnkr.co/edit/q4d7P8Pe9jmgeqDiwqVC?p=preview) with your new hint. Did you mean something like that? – floatingpurr Jul 22 '15 at 15:43