I have an angular object item.add_value = 0 bind into the
<input type="number" ng-model="item.add_value" ng-change="sumUp(item)" min="0" max="10000000000" />
In order to do the calculation I have to use type="number" not type="text"
Then my question is how to hide the content of the input when the value is 0?
I just had this same problem and found a way to fix/improve on @dubadub's answer, so I'm sharing my version of his directive:
.directive('hideZero', function() {
return {
require: 'ngModel',
restrict: 'A',
link: function (scope, element, attrs, ngModel) {
ngModel.$formatters.push(function (inputValue) {
if (inputValue == 0) {
return '';
}
return inputValue;
});
ngModel.$parsers.push(function (inputValue) {
if (inputValue == 0) {
ngModel.$setViewValue('');
ngModel.$render();
}
return inputValue;
});
}
};
})
You just use it by adding the hide-zero
attribute to your inputs.
The simplest (and the weirdest) way to do it is to use ... CSS! Consider this:
<input type="number" ng-model="item.add_value"
ng-class="{zero: item.add_value === 0}"
ng-change="sumUp(item)"
min="0"
max="10000000000" />
and CSS:
.zero {
text-indent: -7px;
}
Not sure it will be appropriate for you, but this is definitely fun and can work if you adjust indent for your font size and input padding.
UDP. One more version using directive:
.directive('hideZero', function() {
return {
link: function(scope, element) {
element.on('input change', function() {
if (this.value === '0') {
this.value = '';
}
})
}
};
});
and use it like:
<input type="number" ng-model="item.add_value"
ng-change="sumUp(item)"
hide-zero
min="0"
max="10000000000" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With