Search code examples
javascriptangularjsangular-ngmodelangularjs-ng-model

ng-model - Empty input returns null


I have this input:

<input ng-model="data.value" type="number" placeholder="0" value="0">

When I changed the input (for example to 1) and then delete it the data.value holds null. I want that when I delete the input data.value will hold 0 as a default value.

I saw this solution: Angular ng-model: empty strings should be null

This is solution will work for me but I want to know if there any other solution without $watch or ng-change function.

Thanks in advance!


Solution

  • If I will have some other inputs and for each input I want other default value I will need to have a lot of directives

    You could have a defaultValue attr for the directive which would be provided while using the directive from HTML. Something like this:

    .directive('emptyToDefault', function () {
        return {
            restrict: 'A',
            require: 'ngModel',
            scope: {
              defaultValue: '='
            },
            link: function (scope, elem, attrs, ctrl) {
                ctrl.$parsers.push(function(viewValue) {
                    if(viewValue === null) {
                        return scope.defaultValue || 0;
                    }
                    return viewValue;
                });
            }
        };
    });
    

    Now you can easily pass different default values from outside and it will be set when string is emptied.

    HTML would be like,

    <input ng-model="data.value" type="number" placeholder="0" value="0" 
           empty-to-default default-value="5">
    

    working plunker (open console to notice how it sets default value 5 since string is emptied and passed value is 5)