PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, October 28, 2022

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

 October 28, 2022     angular-ngmodel, angularjs, is-empty, undefined     No comments   

Issue

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>



Answered By - georgeawg
Answer Checked By - Katrina (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing