Search code examples
angularjsundefinedangular-ngmodelis-empty

How to set automatically input values as empty (instead of "undefined") when the user remove the value?


In Angular 1.6, when the user removes values inside inputs, these values are set up to "undefined". It seems to be the default behaviour in AngularJS.

HTML

<input ng-model="name" class="form-control" id="inp_name"
       placeholder="My Name" required="true" value="" />

Controller

...
$scope.name = ""; <-- here the initial value is correctly set up as empty
...
$scope.submit = function(){
     alert($scope.name); <-- the value can be "undefined" if the user removed all the string
};

How to automatically set up the value as empty instead of "undefined" each time the text input is empty on the front-end ?


Solution

  • Use ng-model-options="{allowInvalid: true}" to allow an empty string when the user deletes all the characters in an input box.

    For more information, see AngularJS ng-model-options Directive API Reference.

    The DEMO

    angular.module("app",[])
    .controller("ctrl", function($scope) {
        $scope.name = "";
    })
    <script src="//unpkg.com/angular/angular.js"></script>
      <body ng-app="app" ng-controller="ctrl">
        <h1>ng-module-options DEMO</h1>
        <input ng-model="name" class="form-control" id="inp_name"
           placeholder="My Name" required="true" value="" 
           ng-model-options="{allowInvalid: true}"
        />
        <br>
        name= {{name === undefined ? 'undefined': name}}
        <br>
        name= {{name === "" ? 'empty string': name}}
      </body>