我想在ng-model中将HTML中的日期格式化为dd-mm-yyyy格式,但我得到的结果是mm-dd-yyyy。我尝试使用插值器,它工作得很好我想知道使用ng-model在HTML本身中以dd-mm-yyyy格式输出输出。
<label class="item item-input">
<input placeholder="Date" type="date" date="dd-MM-yyyy" ng-model="vm.advance.date"></input>
</label>
答案 0 :(得分:1)
angular.module('app', ['ui.bootstrap']).controller('MyController', function() {
this.advance = {
date: new Date()
};
})
&#13;
<script src="//code.angularjs.org/snapshot/angular.min.js"></script>
<script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-2.5.0.js"></script>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<body ng-app="app">
<div ng-controller="MyController as vm">
<label class="item item-input">
<input ng-model="vm.advance.date" ng-value="vm.advance.date | date : 'dd-MM-yyyy'" ng-disabled="true"/>
</label>
<p class="input-group">
<input type="text" class="form-control" is-open="vm.opened" ng-model="vm.advance.date" uib-datepicker-popup="dd-MM-yyyy" ng-required="true" />
<span class="input-group-btn">
<button type="button" class="btn btn-default" ng-click="vm.opened = true"><i class="glyphicon glyphicon-calendar"></i></button>
</span>
</p>
</div>
</body>
&#13;
答案 1 :(得分:1)
这样做的Javascript方式使用$ filter,但即使你使用html或js方式的filter('|'pipe),类型也不是Date的字符串
angular.module('inputExample', [])
.controller('ExampleController', ['$scope', '$filter', function($scope,$filter) {
$scope.advance = $filter('date')(new Date(), 'dd-MM-yyyy');
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="inputExample">
<form name="testForm" ng-controller="ExampleController">
<input placeholder="Date" ng-model="advance"/>
</form>
</body>
答案 2 :(得分:0)
您可以在过滤器中使用值:
{{vm.advance.date | date:'dd-MM-yyyy'}}
实际上更好地使用datepicker。它有更灵活的工具。
答案 3 :(得分:-1)
请查看以下示例。
angular.module('app', [])
.controller('Ctrl', function($scope){
$scope.firstDate = new Date();
$scope.secondDate = "2014-02-20";
})
// Here is where the magic works
.directive('date', function (dateFilter) {
return {
require:'ngModel',
link:function (scope, elm, attrs, ctrl) {
var dateFormat = attrs['date'] || 'yyyy-MM-dd';
ctrl.$formatters.unshift(function (modelValue) {
return dateFilter(modelValue, dateFormat);
});
}
};
})
<强> Demo 强>