Celestialchippy
Celestialchippy

Reputation: 271

AngularJS date in controller undefined

I'm trying to add a date that defaults to the current day to my page. Below is the angular script for this but when I click add day I get error of undefined? I don't understand I believe it's been defined correctly.

$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>

This is what my code looks like.

this is the stack trace from console

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)

Upvotes: 0

Views: 300

Answers (1)

Aleksey Solovey
Aleksey Solovey

Reputation: 4191

You have a typo.

property 'today' of undefined means something has .today, which doesn't exists. In your case it's either $scope.add or $scope.edit

I think while changing your code, you forgot to replace one of them. Try changing:

$scope.edit.today = null;

to

$scope.add.today = null;

Or initialise it, if you are missing it with $scope.edit = {};


Given your edited code, you have a working solution

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>

Upvotes: 1

Related Questions