控制器中的AngularJS日期未定义

时间:2018-06-06 14:53:56

标签: angularjs

我试图将默认为当天的日期添加到我的页面。下面是这个角度脚本但是当我点击添加日时我得到undefined的错误?我不明白我相信它已被正确定义。



$scope.today= new Date();
$scope.add = {};

       if($scope.today){
           var today= new Date($scope.today)
           $scope.add.today=
                today.getFullYear()+'-'+(today.getMonth() + 1)+'-'+today.getDate();
       }else{
           $scope.add.today= null;
       }

<div class="form-group col-sm-4">
      <label for="Date">Date</label>
      <input type="date" class="form-control" name="add_row_today" id="add_row_today" ng-model="today">
</div>
&#13;
&#13;
&#13;

这就是我的代码。

这是来自控制台的堆栈跟踪

TypeError: Cannot set property 'today' of undefined
    at m.$scope.add_list (angularScripts.js?v=1.3:8741)
    at fn (eval at compile (_bower.js?v=1.2:10467), <anonymous>:4:220)
    at b (_bower.js?v=1.2:10360)
    at e (_bower.js?v=1.2:10510)
    at m.$eval (_bower.js?v=1.2:10379)
    at m.$apply (_bower.js?v=1.2:10380)
    at HTMLInputElement.<anonymous> (_bower.js?v=1.2:10510)
    at HTMLInputElement.dispatch (_bower.js?v=1.2:5201)
    at HTMLInputElement.elemData.handle (_bower.js?v=1.2:5009)

1 个答案:

答案 0 :(得分:1)

你有一个错字。

property 'today' of undefined表示某些内容已.today,但不存在。在您的情况下,它可以是$scope.add$scope.edit

我认为在更改代码时,您忘记更换其中一个代码。尝试更改:

$scope.edit.today = null;

$scope.add.today = null;

或初始化它,如果您错过了$scope.edit = {};

根据您编辑的代码,您有一个可行的解决方案

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
  $scope.today = new Date();
  $scope.add = {};

  if ($scope.today) {
    var today = new Date($scope.today)
    $scope.add.today =
      today.getFullYear() + '-' + (today.getMonth() + 1) + '-' + today.getDate();
  } else {
    $scope.add.today = null;
  }
});
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<body>
  <div ng-app="myApp" ng-controller="myCtrl">

    <div class="form-group col-sm-4">
      <label for="Date">Date</label>
      <input type="date" class="form-control" name="add_row_today" id="add_row_today" ng-model="today">
    </div>

  </div>
</body>
</html>