J.BizMai
J.BizMai

Reputation: 2787

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 ?

Upvotes: 0

Views: 4328

Answers (4)

georgeawg
georgeawg

Reputation: 48968

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>

Upvotes: 1

J.BizMai
J.BizMai

Reputation: 2787

An alternative but an automatic way (which seems to be the best) is to use a function to check up if the value is empty, null and undefined.

Controller

$scope.isEmpty = function (value) {
   return angular.equals("", value) || angular.equals(undefined, value) || angular.equals(null, value);
};

//Usage 
$scope.submit = function(){
    if($scope.isEmpty($scope.name)) ...
};

Upvotes: 0

Varun Sukheja
Varun Sukheja

Reputation: 6536

If there is no value in $scope.name (covers undefined) then setting it to empty string

if(!$scope.name){$scope.name="";}

Upvotes: 0

Sletheren
Sletheren

Reputation: 2486

You can add this in your submit function:

$scope.name = $scope.name ? $scope.name : "";

Upvotes: 0

Related Questions