Shri.harry
Shri.harry

Reputation: 287

How to assign value to ng-model if it is empty

I want to assign value to ng-model if it is empty. I have assign default value to ng-model input from controller but when user makes change to remove that value and makes input empty then I want to assign default value to ng-model.

For example.

Controller:

App.controller('mainController',['$scope', function($scope) {
   $scope.assignOne= 16;
}]);

View:

<input ng-model="assignOne" ng-change="changeMe()"/>

Now, input value becomes 16.

If user make changes and manually removes this value 16 then I want default value 1 instead of empty string in changeMe() function.

Note: I can check for empty ng-model and override value of ng-model in controller. But, Is there any way better way to use, something which angular provides.

I am just new to AngularJS.

Upvotes: 1

Views: 1482

Answers (2)

Didier68
Didier68

Reputation: 1323

another solution to meet your sample:

App.controller('mainController',['$scope', function($scope) {

   $scope.assignOne= 16;

   // function called by " ... ng-change="changeMe() "
   $scope.changeMe = function() {
      if ($scope.assignOne == '') {
          $scope.assignOne = 1;
      }
   }
}]);

PS: for the previous answer, there is a little miss: it doesn't change the "assignOne" var, but only a local copy, which is lost at the end of the function call... Correct it by changing $scope.assignOne !

PS 2: the 2 solutions are good, but can resolve different requirements :

  • $watch is like a trigger on the model object, and is the most efficient if you want check business rules on the navigator side

  • ng-change is more interesting for handling some interactions, which are not stricts rules...

The 2 ways could be used...

Upvotes: 0

Partha Sarathi Ghosh
Partha Sarathi Ghosh

Reputation: 11576

Try $watch as follows

$scope.$watch(
   "assignOne",
    function handleChange( newValue, oldValue ) {
          console.log( "assignOne:", newValue );
          if(newValue == '') {
             newValue = 16;
          }
    }
);

Upvotes: 1

Related Questions