我有一个日期输入,由于某种原因,当我尝试在我的范围变量中使用它时,它会变得不确定或“ d-n-u”。 以为我有这个输入的监视,并且值不是在那里未定义。 我似乎无法使它正常工作
html:
<input type="date" id="date-input2" ng-model="params.schedule" />
javaScript:
$scope.$watch('params.schedule', function (newValue, oldValue) {
//here I am indeed getting Mon Dec 31 2018 00:00:00 GMT+0000 (Western European //Standard Time)
console.log(newValue);
console.log($scope.params.schedule);
}, true);
//但是当我尝试使用它时,它变成undefined
...然后是d-n-u
...,因为它
var scheduledDate = $scope.params.schedule;
$scope.params.schedule = scheduledDate[2] + "- " + scheduledDate[1] + "- " + scheduledDate[0];
$scope.ScheduledDate = scheduledDate.substring(0, 10);
为什么价值在中途丢失?
答案 0 :(得分:0)
在$ scope内分配 $scope.params.schedule
的值。$ watch本身而非外部,
$scope.$watch('params.schedule', function (newValue, oldValue) {
//here I am indeed getting Mon Dec 31 2018 00:00:00 GMT+0000 (Western European //Standard Time)
var scheduledDate = $scope.params.schedule;
$scope.params.schedule = scheduledDate[2] + "- " + scheduledDate[1] + "- " + scheduledDate[0];
$scope.ScheduledDate = scheduledDate.substring(0, 10);
}, true);
答案 1 :(得分:0)
我认为JS将日期用作字符串:
var scheduledDate = $scope.params.schedule;
// scheduledDate is now equal to the date object "Mon Dec 31 2018 00:00:00 GMT+0000"
$scope.params.schedule = scheduledDate[2] + "- " + scheduledDate[1] + "- " + scheduledDate[0];
// Now $scope.params.schedule is parsed as a string by JS (you can't iterate on a date object) and equal to the 3rd char of the string, dash, 2nd char, dash, 1st char
// So $scope.params.schedule is equal to d- n- u
除非不在应用程序中使用过多日期,否则我建议您使用momentjs或其他库来处理日期。