1

I receive an object that contains a number: time in seconds from midnight.
I want the object to stay in seconds, but display this time in hours format.

A filter can't be used since it is in an input.
The directive is the way to go. I have found questions here, but they all do it the opposite way (changing the object, not the view): Using angularjs filter in input element

<input type="text" ng-model="time"/>

<script> 

angular.module('app')
.controller('AppController', ['$scope', function($scope){
   $scope.time = "32400";
}]);

</script>

So, input needs to be : 09:00
$scope.time = 32400.

When changing hours, $scope.time needs to change (in seconds)

Community
  • 1
  • 1
gr3g
  • 2,866
  • 5
  • 28
  • 52
  • 1
    I don't understand why the way described in the link won't work. ngModelController.$parsers.push(function(data) { return data * 3600; // More complicated conversion needed here }); ngModelController.$formatters.push(function(data) { return data / 3600; // More complicated conversion needed here }); – bm1729 Jun 22 '15 at 15:05

1 Answers1

0

The Stackoverflow link in my question was resolving my problem, but since the Jsfiddle didn't show the 2 ways of changing data it didn't helped me.
This might help...

<input type="text" ng-model="seconds" seconds-to-time/>

<script> 

angular.module('app')
.controller('AppController', ['$scope', function($scope){
   $scope.seconds= "32400";
}])

.directive('timeToSeconds', function(){
return {
  restrict : 'A',
  require : 'ngModel', // tells Angular that our directive requires the controller of another directive
 link : function(scope, el, attrs, ngModelController){ //We use the controller of ngModel directive!
       //we add methods to the ngModelController

       //From view to model
       ngModelController.$parser.push(function(data){
          return data * x;
       });

       //From model to view
       ngModelController.$formatters.push(function(data){
          return data / x;
       });
}
};
});

</script>
gr3g
  • 2,866
  • 5
  • 28
  • 52