2017-08-29 16 views
0

在Angular 1.6中,当用户删除输入内的值时,这些值被设置为“未定义”。它似乎是AngularJS中的默认行为。如何在用户删除AngularJS 1.6中的值时将输入值自动设置为空(而不是“未定义”)?

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

如何自动设置的值作为空的,而不是“未定义”每次文本输入是在前端空?

回答

1

使用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>

0

您可以在提交功能,补充一点:如果在$ scope.name没有价值

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

(包括未定义),然后将其设置为空字符串

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

的选择,但自动方式(似乎是最好的)是使用函数来检查值是否为空,空值和未定义。

控制器

$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)) ... 
}; 
相关问题