如何在用户删除值时自动将输入值设置为空(而不是 "undefined")?

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

在 Angular 1.6 中,当用户删除输入中的值时,这些值将设置为 "undefined"。这似乎是 AngularJS 中的默认行为。

HTML

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

控制器

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

如何在前端每次文本输入为空时自动将值设置为空而不是 "undefined"?

您可以在提交功能中添加:

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

如果 $scope.name 中没有值(覆盖未定义)则将其设置为空字符串

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

另一种但自动的方法(这似乎是最好的)是使用函数检查值是否为空、null 和未定义。

控制器

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

当用户删除输入框中的所有字符时,使用ng-model-options="{allowInvalid: true}"允许空字符串。

有关详细信息,请参阅 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>