Reputation: 562
I am binding a variable to an input-field of type time, but the displayed format is wrong.
It displays the time like this: 08:54:30,088
What I actually need is a format like this: 08:54
.
I tried to set the value of the input field with a filter ( value={{ datetime.date | date : 'HH:mm' }}
) but my editor says the way I do this is wrong. Any ideas?
Here the compltete code:
<input id="rep_time" class="form-control" type="time" ng-model="datetime.time" value={{ datetime.date | date : 'HH:mm' }}>
app.controller( 'newCtrl', function( $scope ) {
$scope.datetime = {
date: new Date(),
time: new Date()
};
} );
Upvotes: 7
Views: 13390
Reputation: 562
I circumvented the problem by defining the Date()-object a bit. It works but I don't like this way of double defining.
<input class="form-control" type="date" ng-model="datetime.date" placeholder="yyyy-MM-dd" min="2016-01-01" required />
<input class="form-control" type="time" ng-model="datetime.time">
$scope.datetime = {
date: new Date(),
time: ''
};
$scope.datetime.time = new Date(
$scope.datetime.date.getFullYear(),
$scope.datetime.date.getMonth() + 1,
$scope.datetime.date.getDate(),
$scope.datetime.date.getHours(),
$scope.datetime.date.getMinutes() );
with the idea of using a $filter from Jimbrooism I found a shorter way!
$scope.datetime = {
date: new Date(),
time: new Date( $filter( 'date' )( new Date(), 'yyyy-MM-dd HH:mm' ) )
};
Upvotes: 2
Reputation: 105
Try this:
<input id="rep_time" class="form-control" type="time" ng-model="datetime.time" data-ng-value={{ datetime.date | date : 'shortTime'}}>
Upvotes: 1
Reputation: 5273
Pls check out this
var app = angular.module("mainApp", []);
app.controller('mainCtrl', function($scope, $filter){
$scope.datetime = {
date: new Date(),
time: $filter('date')( new Date(), 'HH:mm')
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<div ng-app="mainApp" ng-controller="mainCtrl">
<input id="rep_time" class="form-control" type="time" ng-model="datetime.time" >
</div>
Upvotes: 1
Reputation: 131
Do you need the model to be bound to an input element? Applying filters to input fields usually generates warnings or errors, since filters are one-way, and binding existing value to input and then changing them there is a two-way binding.
If you don't need to be able to change the element, consider changing input to something else, like
<div ng-bind="datetime.date | date : 'HH:mm'"></div>
If you have to use input, Jimbroosim's answer would work.
Upvotes: 0