0

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 ?

0

4 Answers 4

1

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>

Sign up to request clarification or add additional context in comments.

Comments

0

You can add this in your submit function:

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

Comments

0

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

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

Comments

0

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)) ...
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.