1

I am trying to implement an angular directive that will hide zero of field as soon as the <input> 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 <input> is first added to the DOM? How can I find out?

You can check the code out http://plnkr.co/edit/TwraJlxZSd3TeSYscExq?p=preview

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
WABBIT0111
  • 2,233
  • 2
  • 18
  • 30
  • Just leave `test` unassigned. You can try it in your plunkr and the textbox will be empty. – Strelok Aug 05 '15 at 06:53
  • @Strelok This will not work for my application. I still want to be able to display the test data on initial load if it's not zero – WABBIT0111 Aug 05 '15 at 14:52

1 Answers1

2

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

Community
  • 1
  • 1
mofojed
  • 1,342
  • 9
  • 11