K. *_* D. 25 javascript angularjs
如果我使用ng-model输入字段和清空,角套它'',而不是null即使是null前.
这是我的问题,因为null如果输入字段为空,我需要发送到服务器,而不是''.
有没有办法告诉角度设置"空"输入模型null?
Mik*_*378 46
您可能想要$watch为空值并将其设置为null:
<input type="text" ng-model="test.value" />
Run Code Online (Sandbox Code Playgroud)
$scope.$watch('test.value', function (newValue, oldValue) {
if(newValue === "")
$scope.test.value = null;
});
Run Code Online (Sandbox Code Playgroud)
另一种方法是使用自定义指令并$parsers在其中应用:
<input type="text" ng-model="test.value" empty-to-null />
Run Code Online (Sandbox Code Playgroud)
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;
});
}
};
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
26637 次 |
| 最近记录: |