ng-model - 空输入 returns null

ng-model - Empty input returns null

我有这个输入:

<input ng-model="data.value" type="number" placeholder="0" value="0">

当我更改输入(例如更改为 1)然后将其删除时 data.value 持有空。我希望当我删除输入时 data.value 将保持 0 作为默认值。

我看到了这个解决方案: Angular ng-model: empty strings should be null

这个解决方案对我有用,但我想知道是否还有其他没有 $watchng-change 功能的解决方案。

提前致谢!

This is solution will work for me but I want to know if there any other solution without $watch

你发现的 link 也有使用 $watch

的解决方案

如果你想使用ng-change

试试这个

<input ng-model="data.value" type="number" ng-change="defaultValue()" 
placeholder="0" value="0">

//控制器

$scope.defaultValue=function()
{
  if($scope.data.value==null || $scope.data.value==='')
  {
    $scope.data.value=0;
  }
}
  • 但是Directive是比其他选项更好的方法之一

If I will have some other inputs and for each input I want other default value I will need to have a lot of directives

您可以为指令设置一个 defaultValue 属性,在使用 HTML 中的指令时会提供该属性。像这样:

.directive('emptyToDefault', function () {
    return {
        restrict: 'A',
        require: 'ngModel',
        scope: {
          defaultValue: '='
        },
        link: function (scope, elem, attrs, ctrl) {
            ctrl.$parsers.push(function(viewValue) {
                if(viewValue === null) {
                    return scope.defaultValue || 0;
                }
                return viewValue;
            });
        }
    };
});

现在您可以轻松地从外部传递不同的默认值,并在字符串为空时设置。

HTML 就像,

<input ng-model="data.value" type="number" placeholder="0" value="0" 
       empty-to-default default-value="5">

working plunker(打开控制台注意它如何设置默认值 5 因为字符串被清空并且传递的值为 5