【问题标题】:I can't get the date from date input value to another var angularjs我无法从日期输入值获取日期到另一个 var angularjs
【发布时间】:2018-12-28 11:38:29
【问题描述】:

当我尝试在我的范围变量中使用时,我有一个日期输入,由于某种原因,它一直变得未定义或“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);

为什么中途会丢失价值?

【问题讨论】:

  • scheduledDate 的值是多少?
  • @Sajeetharan "undefined- undefined- undefined"
  • 尝试为此提供 plunkr。理解起来会更有帮助。
  • 不使用观察者,而是使用ng-change 指令。它只在用户输入时触发。

标签: javascript angularjs date


【解决方案1】:

$scope.params.schedule 的值分配在 $scope.$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);

【讨论】:

    【解决方案2】:

    我认为日期被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 或其他库来处理日期,除非您在应用程序中不经常使用它们。

    【讨论】:

      猜你喜欢
      • 2019-08-19
      • 2020-09-18
      • 1970-01-01
      • 2014-10-26
      • 1970-01-01
      • 2023-03-31
      • 2016-04-19
      • 1970-01-01
      • 2017-11-22
      相关资源
      最近更新 更多