I have defined custom filter to format input number to specific format i.e. hh:mm
filter
app.filter('formatDuration', function () {
return function (duration) {
if (angular.isUndefined(duration) || duration === null || duration.toString().trim() == '') return '';
var hour = Math.floor(duration / 60);
var min = duration % 60;
if (min < 10) {
min = '0' + min;
}
return hour + ':' + min;
};
});
However, if i am unable to bind it with my input type = text field data-ng-model = "myModel"
.
When i enter something in input field's data-ng-model, it does not connect with my filter.
<input type="text" name="Duration" class="form-control" data-ng-model="{{Duration | formatDuration" />
But, if i bind it with value e.g. value = "{{data-ng-model = Duration | formatDuration}}"
than it connects with my custom filter and do the required conversion but does not show formatted value inside input field instead shows what originally entered..
<input type="text" name="Duration" class="form-control" data-ng-model="Duration" value="{{Duration | formatDuration}}" />
So, i have few points to be clarified
1) Can i bind customer filter with data-ng-model? As per AngualrJs site Yes it should be 2) If so, than where i am wrong?
May be it is worth to mention that my input field is inside ng-repeat...
When you think about it... if you'd apply filter to your bound variable then it would be formatted when ever you type in something. Now if you type "1", you'd end up having formatted value of "0:01". Nice but this would then trigger filter again and you'd end up with "NaN:NaN".
You could use your custom filter and make it work by using e.g. ng-blur
directive on your template, so filtering would only happen once.
<input type="text"
class="form-control"
ng-blur="formatDuration(duration)"
data-ng-model="duration">
Where formatDuration
would be fn
$scope.formatDuration = function(duration) {
$scope.duration = $filter('formatDuration')(duration);
}