2

I am having trouble formatting a date in a read-only field using AngularJS. This is my html code -

        <div class="row">
            <label class="col-md-2">Date Last Login:</label>
            <div class="col-md-3">
                <input type="datetime" name="dateLastLogin" class="form-control" data-ng-model="loginDate" readonly />
            </div>
        </div>

I have tried to format it using this code in my controller -

$scope.$watch('vm.account.dateLastLogin', function(newValue) {
    $scope.loginDate = $filter('date')(newValue, 'MM/DD/yyyy');
});

Putting a break point in the controller, I see the function being called but nothing is displayed.

If I leave my html like this -

        <div class="row">
            <label class="col-md-2">Date Last Login:</label>
            <div class="col-md-3">
                <input type="text" name="dateLastLogin" class="form-control" data-ng-model="vm.account.dateLastLogin" readonly />
            </div>
        </div>

I get a displayed value that includes the date and time but not formatted as I need it. What am I missing?

Craig
  • 1,205
  • 2
  • 21
  • 54

1 Answers1

3

According to this answer, the W3C removed the datetime input type from the HTML5 Specification. date and datetime-local are still valid.

In your example, throw out the formatting filter and simply use the ng-model="vm.account.dateLastLogin" on a valid date input, like:

<input type="date" ng-model="vm.account.dateLastLogin" />

or

<input type="datetime-local" ng-model="vm.account.dateLastLogin" />

These date formats are formatted correctly to the client browsers locale.

Or, if you actually just want it in some text field, put the filter directly in the ng-model but still use a valid Date object, like:

<input type="text" ng-model="vm.account.dateLastLogin | date:'MM/dd/yyyy'" readonly />

See this jsBin for some examples

Community
  • 1
  • 1
Tom
  • 7,640
  • 1
  • 23
  • 47
  • Putting a filter in the ng-model produce an error on the page (it does work, but with error), do you know why? "runner-3.35.12.min.js:1 Error: [ngModel:nonassign]..." – GoldenAxe Apr 23 '16 at 20:02