我想将今天的日期添加为文本框的值。我有一个以dd / mm / yyy(2017年3月23日)显示日期的指令。格式。 的 Direcive: -
app.directive('formatDateInModel', function($filter) {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, element, attrs, ngModel) {
ngModel.$formatters.push(function(value) {
var returnDate = "";
if (value) {
returnDate = $filter('date')(new Date(value), 'dd/MM/yyyy');
}
return returnDate;
});
}
};
});
默认情况下我今天需要日期,所以我返回以下代码来显示今天的日期。但它显示无效日期。
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10) {
dd='0'+dd
}
if(mm<10) {
mm='0'+mm
}
today = mm+'/'+dd+'/'+yyyy;
$scope.ng-model = today;
答案 0 :(得分:1)
你可以直接使用带有过滤器的日期,如下所示
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.date = new Date();
});
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js@1.4.x" src="https://code.angularjs.org/1.4.12/angular.js" data-semver="1.4.9"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<input type="text" ng-model="date | date:'dd/MM/yyyy'"/>
{{date | date:'dd/MM/yyyy'}}
</body>
</html>
答案 1 :(得分:0)
你可以试试这个
Date.prototype.today = function () {
return ((this.getDate() < 10)?"0":"") + this.getDate() +"/"+(((this.getMonth()+1) < 10)?"0":"") + (this.getMonth()+1) +"/"+ this.getFullYear();
}
var newDate = new Date();
var datetime = newDate.today();
document.write(datetime);
答案 2 :(得分:0)
在控制器中使用过滤器:
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope,$filter) {
$scope.date = new Date();
$scope.date =$filter('date')($scope.date, "dd/MM/yyyy");
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<input type="text" ng-model="date" />
</body>
</html>
&#13;