ng-model - Empty input returns null

Sagie picture Sagie · May 3, 2017 · Viewed 8.5k times · Source

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!

Answer

Ramesh Rajendran picture Ramesh Rajendran · May 3, 2017

This is solution will work for me but I want to know if there any other solution without $watch

The link what you found, also had a solution with using $watch


If you want to use ng-change

Jus try this

<input ng-model="data.value" type="number" ng-change="defaultValue()" 
placeholder="0" value="0">

// controller

$scope.defaultValue=function()
{
  if($scope.data.value==null || $scope.data.value==='')
  {
    $scope.data.value=0;
  }
}
  • But Directive is one of the best way than other options