2017-08-29 73 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)) ... 
}; 
相關問題