Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ng-model: empty strings should be 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.

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?

like image 933
K. D. Avatar asked Aug 16 '14 21:08

K. D.


People also ask

Does empty string mean 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.

Why use NULL instead of empty string?

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.

Which is better empty string or NULL?

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.


1 Answers

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;             });         }     }; }); 
like image 93
Mik378 Avatar answered Oct 02 '22 16:10

Mik378