AngularJS directives to hide zero when <input&g

2019-08-12 04:12发布

问题:

I am trying to implement an angular directive that will hide zero of field as soon as the is on DOM. basically this

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

my code look something like this : <input hide-zero-onload ng-model="test"></input>

.directive('hideZeroOnload', function() {
    return {
        link: function(scope, element) {
            element.on('input load', function() {
                console.log('loaded');
                if (this.value === '0') {
                    this.value = '-';
                }
            });
        }
    };
});

However,the console log is never printed. I also tried 'input onload', 'input init', 'input all', and 'input', with all the same result. I don't know what event keyword is emitted when the is first added to the DOM? or how can I find out? You can check the code out http://plnkr.co/edit/TwraJlxZSd3TeSYscExq?p=preview

回答1:

Take a look at $formatters for this purpose. They are designed to format the view of the model when the model is changed or initially loaded. Plunkr http://plnkr.co/edit/SA9xz6eQmk3t7qfRack7?p=preview

Your directive would then look something like this:

.directive('hideZero', [ function() {
    return {
      require: '?ngModel', // get a hold of NgModelController
      link: function(scope, element, attrs, ngModel) {

        // Specify how UI should be updated
        ngModel.$formatters.push(function(value) {
          if (value === 0) {
            // If the value is zero, return a blank string.
            return '';
          }

          return value;
        });
      }
    };
  }]);

The load event may not fire for all elements. Jquery on() load event on a single element