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.
This is a problem in my case because I need to send null
to the server if the input field is empty, and not ''
.
Is there a way to tell angular setting "empty" input models to null
?
The Java programming language distinguishes between null and empty strings. An empty string is a string instance of zero length, whereas a null string has no value at all. An empty string is represented as "" . It is a character sequence of zero characters.
If you were to use s , it would actually have a value of null , because it holds absolute nothing. An empty string, however, is a value - it is a string of no characters. Null is essentially 'nothing' - it's the default 'value' (to use the term loosely) that Java assigns to any Object variable that was not initialized.
So it is better to use empty string for database as allowing NULL value forces the system to do extra work and does not give the data that you are looking for. However, NULL does not throw any exception when the count() function is executed.
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; });
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; }); } }; });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With