输入默认为零 - 不允许空值

时间:2014-07-24 07:47:15

标签: angularjs

我在这个输入字段上使用了几个指令:

<input valid-number  type="tel" ng-model="planBody.campaign.campaignparams.budget" currency-input=""/>

以下指令似乎是在所有类型的模型更新中重置空或“”为“0”,无论是通过用户按键还是JavaScript:

.directive('currencyInput', function($filter, $browser) {
    return {
        require: 'ngModel',
        link: function($scope, $element, $attrs, ngModelCtrl) {
            var listener = function() {
                var value = $element.val().replace(/,/g, '');
                $element.val($filter('number')(value, false));
            };

            // This runs when we update the text field
            ngModelCtrl.$parsers.push(function(viewValue) {
                return viewValue.replace(/,/g, '');
            });

            // This runs when the model gets updated on the scope directly and keeps our view in sync
            ngModelCtrl.$render = function() {
                $element.val($filter('number')(ngModelCtrl.$viewValue, false));
            };

            $element.bind('change', listener);
            $element.bind('keydown', function(event) {
                var key = event.keyCode;
                // If the keys include the CTRL, SHIFT, ALT, or META keys, or the arrow keys, do nothing.
                // This lets us support copy and paste too
                if (key == 91 || (15 < key && key < 19) || (37 <= key && key <= 40)){
                  return;
                }
                $browser.defer(listener); // Have to do this or changes don't get picked up properly
            });

            $element.bind('paste cut', function() {
                $browser.defer(listener);  
            });
        }

    };
})

.directive('validNumber', function() {
  return {
    require: '?ngModel',
    link: function(scope, element, attrs, ngModelCtrl) {
      if(!ngModelCtrl) {
        return; 
      }

      ngModelCtrl.$parsers.push(function(val) {
        var clean = val.replace( /[^0-9]+/g, '');
        if (val !== clean) {
          ngModelCtrl.$setViewValue(clean);
          ngModelCtrl.$render();
        }
        return clean;
      });

      element.bind('keypress', function(event) {
        if(event.keyCode === 32) {
          event.preventDefault();
        }
      });
    }
  };
})

我想在输入字段中允许空值。指令的哪一部分应该改变?

1 个答案:

答案 0 :(得分:1)

问题出现在最顶端,你有$element.val($filter('number')(value, false))

您正在过滤value并将其设置为$element。如果过滤并将字符串清空为数字,则它变为零。

如果您不想这样,那么我建议您在过滤前进行测试:

// Check to see if value is null or empty.
// If it is, then just assign the value to be an empty string.
// Otherwise, filter the number.
// Here I am using UnderscoreJS for the null/empty check, but you can use pure javascript.
value = (_.isNull(value) || _.isEmpty(value)) ? '' : $filter('number')(value);

// Now assign the new value
$element.val(value);