2017-08-29 3 views
0

角度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 : ""; 
0

を$のscope.nameに値がない場合は、空の文字列

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

代替だけに、それを設定(未定義のカバー)自動的な方法(これが最善の方法です)は、値が空、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)) ... 
}; 
関連する問題