Radziasss Radziasss - 6 months ago 13
Javascript Question

Angularjs: setting datetime-local correctly, but submitting null

I'm trying to set default values for two input datetime-local fields. I'm using angularjs 1.5.5. My .jsp code looks like this:

<div class="row">
<div class="form-group col-md-12">
<label class="col-md-2 control-label" for="dateTo">Date to</label>
<div class="col-md-7">
<input type="datetime-local" ng-model="ctrl.map.dateTo" id="dateTo" class="form-control input-sm" />
</div>
</div>
</div>


(similar for the second field)

This is my js script that sets fields:

$(document).ready(function(){
var now = new Date();

var timestampDateTo = now.getTime() - now.getTimezoneOffset()*60000;
var timestampDateFrom = now.getTime() - now.getTimezoneOffset()*60000 - 2*60*60*1000;

var dateTo = new Date(timestampDateTo);
var dateFrom = new Date(timestampDateFrom);

$("input[id=dateTo]").val(dateTo.toISOString().substring(0,19));
$("input[id=dateFrom]").val(dateFrom.toISOString().substring(0,19));
});




I'm getting
nicely filled date fields,

enter image description here

So far so good, but when I submit my form, this fields are send by
nulls.

enter image description here
Why is that? Note that when I set this fields 'by hand', they are submitting properly.

Answer

This is because of how you are setting the values, you are changing the DOM directly and Angular has not picked up the change, you should change the ng-model object, and not the DOM. In your controller/Angular code you should have something like:

var now = new Date();

var timestampDateTo   = now.getTime() - now.getTimezoneOffset()*60000;
var timestampDateFrom = now.getTime() - now.getTimezoneOffset()*60000 - 2*60*60*1000;

var dateTo = new Date(timestampDateTo);
var dateFrom = new Date(timestampDateFrom);

$scope.ctrl.map.dateTo = dateTo;

You should avoid setting DOM values directly when using Angular, it's not good practice, it's better to update the Angular value in the scope and have Angular update the DOM for you