Moussa
Moussa

Reputation: 4154

Angular bind string date to input type date

I am using Angular 1.6 and I would like to directly bind a string to an input of type date instead of having to convert the date to a Date and then bind to the input. The reason is that I get JSON (along with other data) from the server and I don't want to create an intermediary variable only for the date, I want to use directly the JSON, and thus I can POST back my JSON as is when there are modifications in input field and no need to use ng-change and convert date and put it my JSON, etc... I have plunkered my issue.

Here is the html :

<body ng-app="plunker" ng-controller="MainCtrl">
  <form name="myForm">
    <label for="exampleInput">Date input</label>
    <input type="date" id="exampleInput" name="input" ng-model="date" placeholder="yyyy-MM-dd"/>
  </form>
</body>

And here is the javascript :

var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
  $scope.dateString = '2017-01-31';
  $scope.date = new Date(2017, 11, 31);
});

If I bind the input to variable $scope.date it is OK but it is KO if I bind it to variable $scope.dateString.

Upvotes: 1

Views: 4509

Answers (2)

Salad.Guyo
Salad.Guyo

Reputation: 3395

Placeholder attribute does not work with input type date. You can achieve this by changing your input type to text.

  <input type="text" onfocus="(this.type='date')" placeholder="{{some_date_holder}}"/>

Read this for more details.

Upvotes: 0

JeanJacques
JeanJacques

Reputation: 1754

You can do it by using value attribute of your input like this :

angular
  .module('plunker', [])
  .controller('MainCtrl', function($scope) {
    $scope.dateString = '2017-01-31';
    $scope.date = new Date(2017, 11, 31);
  })
;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<section ng-app="plunker" ng-controller="MainCtrl">
  
  <form name="myForm">
    <label for="exampleInput">Date input</label>
    
    <input 
      type="date" value="{{dateString | date : 'yyyy-MM-dd'}}" 
      ng-model="dateString" placeholder="yyyy-MM-dd"
    />
  </form>
  
</section>

Upvotes: 2

Related Questions