Fima Taf Fima Taf - 3 months ago 17
AngularJS Question

AngularJS date input with date from json

I have an issue with getting date from json and integrate it with

<input>
tag.
I have a json object that has the 'date' value like this -
dd/mm/yyyy
and it doesn't show me that date in the html, and when I press on the 'Edit' button it doesn't receive this date.

JSON





{
"books":[
{
"title": "Harry Potter and the Philosopher's Stone",
"author": "J. K. Rowling",
"date": "26/06/1997"
}
]
}







<tr ng-repeat="book in recivedBooks">
<td>
<span class="date" ng-hide="editMode">Realease Date: {{book.date}}</span>
<input class="form-control input-lg" name="date" type="date" placeholder="dd/mm/yyyy" ng-show="editMode" ng-model="book.date" required>
</td>
</tr>





Is there a way to parse the date from the json, show it in the html and then when you press on the 'Edit' button it will automatically will go to the
<input>
?

Answer

string date from json have to convert into javascritp Date format.

<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="datCtrl">
  <button ng-click=edit()>Edit</button>
<table>
  <tr ng-repeat="book in recivedBooks">
   <td>
     <span class="date" ng-hide="editMode">{{book.Name}}  Realease Date: {{book.date | date:'dd/MM/yyyy'}}</span>
     
     <input class="form-control input-lg" name="date" type="date" placeholder="dd/mm/yyyy" ng-show="editMode" ng-model="book.date" required>
   </td>
</tr>
  
  </table>


</div>

<script>
var app = angular.module('myApp', []);
app.controller('datCtrl', function($scope) {
  $scope.editMode=false;
  var json = [
  {Name: 'book 1',date:'02/11/2016'},
  {Name: 'book 2',date:'05/11/2016'}
  ]; // if json file like this
  
  $scope.recivedBooks=[];
  
  var totalBook = json.length;
  
  for(var i=0; i < totalBook; i++){
    var newDateFormate = json[i].date.split("/");
    var date = new Date(newDateFormate[2],newDateFormate[1],newDateFormate[0]);
  $scope.recivedBooks.push({Name:json[i].Name,date:date})
  }
  
  
  $scope.edit= function(){
   $scope.editMode = !$scope.editMode;
  }
});
</script>

<p>The date filter formats a date object to a readable format.</p>

</body>
</html>