ng-model:空字符串应该为空 [英] ng-model: empty strings should be null
本文介绍了ng-model:空字符串应该为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我使用 ng-model
作为输入字段并将其清空,angular 会将其设置为 ''
而不是 null
,即使它是之前是 null
.
If I use ng-model
for an input field and empty it, angular sets it to ''
instead of null
even if it was null
before.
这对我来说是个问题,因为如果输入字段为空,我需要将 null
发送到服务器,而不是 ''
.
This is a problem in my case because I need to send null
to the server if the input field is empty, and not ''
.
有没有办法告诉角度设置空"输入模型为null
?
Is there a way to tell angular setting "empty" input models to null
?
推荐答案
您可能希望 $watch
为空值并将其设置为 null
:
You may want to $watch
for the empty value and set it to null
:
<input type="text" ng-model="test.value" />
$scope.$watch('test.value', function (newValue, oldValue) {
if(newValue === "")
$scope.test.value = null;
});
另一种方法是使用自定义指令并在其中应用 $parsers
:
Another way would be to use a custom directive and apply a $parsers
in it:
<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;
});
}
};
});
这篇关于ng-model:空字符串应该为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文