How to format input value [time] when binding to Date () - object

I bind a variable to an input field of type time, but the displayed format is incorrect.

Displays the time, like this: 08:54:30,088 I really need a format 08:54.

I tried to set the value of an input field with a filter ( value={{ datetime.date | date : 'HH:mm' }}), but my editor says that I am doing it wrong. Any ideas?

Here is the compltete code:

HTML

 <input id="rep_time" class="form-control" type="time" ng-model="datetime.time" value={{ datetime.date | date : 'HH:mm' }}>

Js

 app.controller( 'newCtrl', function( $scope ) {  

     $scope.datetime = {
         date: new Date(),
         time: new Date()
       };
 } );
+4
source share
4 answers

I got around the problem by slightly changing the date () of the object. It works, but I do not like this double-definition method.

HTML

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

Js

$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() );

UPDATE js

with the idea of ​​using the $ 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' ) )
   };
+1

Pls

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>
Hide result
+1

:

<input id="rep_time" class="form-control" type="time" ng-model="datetime.time" data-ng-value={{ datetime.date | date : 'shortTime'}}>
+1

Do you need a model to bind to an input element? Applying filters to input fields usually generates warnings or errors, since the filters are unidirectional and bind the existing value for input, and then change them, there is a two-way binding.

If you don’t need to change the item, consider changing the input to something else, for example

<div ng-bind="datetime.date | date : 'HH:mm'"></div>

If you need to use input, Jimbroosim's answer will work.

0
source

All Articles