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

后端 未结 7 2075
北恋
北恋 2020-12-19 15:56

I have an angular object item.add_value = 0 bind into the



        
7条回答
  •  青春惊慌失措
    2020-12-19 16:40

    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.

提交回复
热议问题