如果我使用ng-model
输入字段和清空,角套它''
,而不是null
即使是null
前。
在我的情况下,这是一个问题,因为null
如果输入字段为空(而不是空),则需要发送到服务器''
。
有没有办法告诉角度设置“空”输入模型null
?
您可能需要$watch
输入空值并将其设置为null
:
<input type="text" ng-model="test.value" />
$scope.$watch('test.value', function (newValue, oldValue) {
if(newValue === "")
$scope.test.value = null;
});
另一种方法是使用自定义指令并$parsers
在其中应用a :
<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;
});
}
};
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句