javascript - ng-型号 : empty strings should be null

标签 javascript angularjs

如果我使用 ng-model 作为输入字段并将其清空,则 Angular 将其设置为 '' 而不是 null,即使它之前为 null

这对我来说是一个问题,因为如果输入字段为空,我需要将 null 发送到服务器,而不是 ''

有没有办法告诉 Angular 设置“空”输入模型为null

最佳答案

您可能需要$watch查找空值并将其设置为null:

<input type="text" ng-model="test.value" />
$scope.$watch('test.value', function (newValue, oldValue) {
  if(newValue === "")
    $scope.test.value = null;
});

另一种方法是使用自定义指令并在其中应用 $parsers:

<input type="text" ng-model="test.value" empty-to-null />
myApp.directive('emptyToNull', function () {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, elem, attrs, ctrl) {
            ctrl.$parsers.push(function(viewValue) {
                if(viewValue === "") {
                    return null;
                }
                return viewValue;
            });
        }
    };
});

关于javascript - ng-型号 : empty strings should be null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25344368/

相关文章:

javascript - 计算前导空间和

javascript - JS `this` 函数调用

javascript - Node `fs.appendFile` 是原子的吗?

javascript - 如何在 Javascript 中提醒 PHP echo

javascript - 跟踪窗口调整大小 AngularJS 上的元素宽度

javascript - 使用 MooTools 完全删除类

javascript - Angular js html不更新

javascript - 迭代数组 Angular

javascript - ng-click后如何将值传递给ng-if?

javascript - angularjs指令在链接函数内使用参数