AngularJS directives to hide zero when <input> is initially loaded to the DOM

泄露秘密 提交于 2019-12-11 13:10:29

问题


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



来源:https://stackoverflow.com/questions/31823569/angularjs-directives-to-hide-zero-when-input-is-initially-loaded-to-the-dom

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!