AngularJs, load saved json date string as object (part 2)

About solution

The solution of the problem within i described in Angular 1.x, how to load saved json string model with date as object (part 1) eg. error ngModel:datefmt Model is not a date object.

Solution

Previous case:

	

angular.module('app', [])
.controller('MainControllers', ['$scope', function($scope) {
	$scope.example = {
	 value: new Date(2015, 11, 30)
	};

	//helper methods
	$scope.DateTime = new Date();

	$scope.Date = function(arg){
		console.log('Date from string:', arg);
		var dt = new Date(arg);
		if (dt.toString() === 'Invalid Date') {
			dt = false;
		}
		return dt;
	};
}]);

Angular convert the model to JSON string like this and send it to the api

	
		{
		  "example": {
		    "value": "2015-11-30T23:00:00.000Z"
		  }
		}
	
	
		 <input type="datetime-local" ng-model="example.value" />
	

When we load those api data into model and form with input type = datetime, we’ll see error ngModel:datefmt Model is not a date object.

For fix it we should use ng-init like this:

	
		 <input type="datetime-local" ng-init="example.value = Date(example.value) || DateTime" />