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.
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;
});
}
};
});