Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide Value in input when it's zero in angular Js

Tags:

angularjs

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?

like image 743
Ricc Avatar asked Dec 05 '22 23:12

Ricc


2 Answers

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.

like image 63
R. Kazeno Avatar answered Dec 20 '22 14:12

R. Kazeno


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.

Demo: http://plnkr.co/edit/2gRzdY7DVwrPdNGoD0Fq?p=preview

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

Demo: http://plnkr.co/edit/nrE3vEW2NSuLYeZuKIjO?p=preview

like image 45
dfsq Avatar answered Dec 20 '22 13:12

dfsq