2017-04-25 63 views
-1

當用戶點擊提交按鈕時,我正在驗證表單,使用ng-click我正在調用函數,在這個函數中我傳遞了form1。$ invalid,根據這個變量,我提出了條件,如果條件爲true,validate函數會調用,這裏的問題是移動的隱藏字段,這個隱藏字段也檢查validation.how可以跳過或不驗證移動字段的隱藏狀態,我嘗試了下面的代碼。如何在ng-click中不驗證隱藏字段?

HTML ----

<form name="form1" novalidate> 
    <input ng-show="user" type="text" name="user" ng-model="frm1.user" /> 
    <p ng-show="form1.user.$error.required"><span ng-show="errorMsgShow" ng-required="true">{{requiredMsg}}</span></p> 
    <input ng-show="mobile" type="text" name="mobile" ng-model="frm1.mobile" /> 
    <p ng-show="form1.mobile.$error.required"><span ng-show="errorMsgShow" ng-required="true">{{requiredMsg}}</span></p> 
    <button ng-click="SubmitForm(regForm.$invalid);">submit</button> 
</form> 

腳本----

$scope.SubmitForm = function(val){ 

$scope.user= true; 
$scope.mobile = false; 
if (if(val ===true){ 
      $scope.validation(); 
    } 
} 
$scope.validation = function(){ 
    $scope.requiredMsg="input fieldis required"; 
} 

回答

0

我認爲更好的方法將採取移動輸入表單的時候使用是不必要的NG-如果而不是隻是用ng-show隱藏它。

Ng-if將確保當條件爲false時,輸入不會在DOM樹中呈現,因此將不會驗證觸發。

您可以對ng-if和ng-show之間的差異進行一些研究,以更好地理解這兩個指令。

+0

我怎麼能做到這一點,請大家幫我 –

+0

移動領域將只顯示用戶選擇特定的國家,如「美國,英國,印度等明智它會隱藏起來。 –

+0

@ ramesh1226使用ng-if =「mobile」和ng-if =「user」代替ng-show – Jenny

0

嘗試ng-if以避免驗證。如果您希望移動設備跳過驗證,請使用表達式將ng-if設置爲false。

語法:NG-IF = 「表達」

去這個鏈接,進一步信息

https://docs.angularjs.org/api/ng/directive/ngIf

的差異NG-如果和NG-隱藏/ NG秀參考下面的鏈接

what is the difference between ng-if and ng-show/ng-hide

+0

現在我明白了,但是,它試過了 - 如果還有,但直到它不工作 –

+0

添加一個JSFiddle我可以從我的最後檢查 – Vishnu

0

一些意見:

  • 而不是使用ng-show隱藏和顯示輸入只使用<input type="hidden"... >元素mobile領域。
  • 無需使用變量$scope.user$scope.mobile來隱藏和顯示輸入。
  • user輸入字段中添加required屬性,而不是在mobile輸入字段中,因爲您不想驗證移動field
  • 使用SubmitForm(form1.$invalid)而不是SubmitForm(regForm.$invalid),因爲您的表單名稱爲form1而不是regForm

DEMO

var myApp = angular.module('myApp',[]); 
 

 
myApp.controller('MyCtrl', function($scope) { 
 
    $scope.SubmitForm = function(val) { 
 
     console.log(val); 
 
     if(val === true) { 
 
      $scope.validation(); 
 
     } 
 
    } 
 
$scope.validation = function() { 
 
    $scope.requiredMsg="input fieldis required"; 
 
} 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
<div ng-app="myApp" ng-controller="MyCtrl"> 
 
    <form name="form1" novalidate> 
 
    <input type="text" name="user" ng-model="frm1.user" required/> 
 
    <p ng-show="form1.user.$error.required">{{requiredMsg}}</p> 
 
    <input type="hidden" name="mobile" ng-model="frm1.mobile" /> 
 
    <button ng-click="SubmitForm(form1.$invalid);">submit</button> 
 
</form> 
 
</div>