Angularjs:使用ng-model输入的angularjs中的日期类型返回unifined

时间:2017-02-02 10:03:57

标签: javascript angularjs

大家好,我有一些问题,一起使用日期类型和ng模型。在我的index.html中我有这样的输入字段:

<input class="form-control" type="date" id="date" ng-model="myData.date" />
<button type="submit" class="btn btn-primary" ng-click="myExample()">Submit</button>

和我的控制员:

$scope.myExample = function() {
    console.debug('date : ', $scope.myData.date);
}

在我的控制台中我得到日志“date:undefined”

为什么我有未定义的价值似乎是什么问题?感谢

顺便使用“bootstrap-datepicker”

3 个答案:

答案 0 :(得分:1)

您必须初始化myData对象

&#13;
&#13;
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
  $scope.myData = {}; //Create the object 
  $scope.myExample = function() {
    console.log('date : ', $scope.myData.date);
  }
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">

  <input class="form-control" type="date" id="date" ng-model="myData.date" />
  <button type="submit" class="btn btn-primary" ng-click="myExample()">Submit</button>

</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

另一种解决方案是将日期值传递给您的函数。

这就是我实现这一目标的方式。

CODE:

<!DOCTYPE html>
<html ng-app="myApp">

  <head>
    <link rel="stylesheet" href="style.css">
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
  </head>

  <body ng-controller="myController">
    <input class="form-control" type="date" id="date" ng-model="myData.date" />
<button type="submit" class="btn btn-primary" ng-click="myExample(myData.date)">Submit</button>
<script>

  angular.module("myApp",[])
  .controller("myController",function($scope){
    $scope.myExample = function(date) {
      console.log(date);
    alert(date);
}

  })
</script>
  </body>

</html> 

您还可以使用angularjs中提供的日期过滤器。请参阅此处的文档 https://docs.angularjs.org/api/ng/filter/date

答案 2 :(得分:0)

以下是使用 bootstrap-datepicker

所需的解决方案

[
  {"_class" : "com.example.domains.User",
   "id": 1,
   "username": "Admin",
   "password": "123Admin123",
   "activated":true
  },
  {
    "_class" : "com.example.domains.Roles",
    "id": 1,
    "user":{"_class" : "com.example.domains.User",
            "id": 1,
            "username": "Admin",
            "password": "123Admin123",
            "activated":true
          },
    "role": "Admin"
  }
]
String rawDate = "2013-07-29 14:49:53.813588954 +0200";
DateTimeFormatter rawDateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.nnnnnnnnn Z");
ZonedDateTime zonedDateTime = ZonedDateTime.parse(rawDate, rawDateFormatter);
System.out.println(zonedDateTime); // prints 2013-07-29T14:49:53.813588954+02:00

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
System.out.println(zonedDateTime.format(formatter)); // prints 2013-07-29 14:49

请运行以上代码段

HERE IS A WORKING DEMO