如果我使用 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/