28

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?

Alexander Abakumov
  • 13,617
  • 16
  • 88
  • 129
K. D.
  • 4,041
  • 9
  • 48
  • 72

1 Answers1

48

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;
            });
        }
    };
});
kapace
  • 457
  • 7
  • 12
Mik378
  • 21,881
  • 15
  • 82
  • 180
  • Ok, you may configure the scope as isolated in the directive to have a better encapsulation. – Mik378 Aug 16 '14 at 22:10
  • This directive works, but only if the input was changed. If the view was loaded and input untouched then still when getting this value in the controller it will be empty string instead of null. Any ideas how to fix this? – Episodex Apr 17 '15 at 10:47
  • 1
    You could simply add this at the top of the link function: `if(scope.value === '') scope.value = null;` – Mik378 Apr 17 '15 at 10:55
  • Thanks for answer. I tried but it doesn't work. `scope` does not contain `value`. Should it be some isolated scope? – Episodex Apr 19 '15 at 10:05
  • In this example, it's assumed that the contextual scope contains a `value` property. As this directive simply reads one value (no assignment), it's unnecessary to make an isolate scope. – Mik378 Feb 26 '16 at 10:50