2016-06-28 19 views
0

我正在寫一個簡單的表單,我想要將表單結果保存到一個數組中,同時更新名字和姓氏,如果其中一個或兩個字段留空應該發出警告消息。數組不應該存儲空值,我想在客戶端處理這個問題。我有點困惑於如何在存儲它們之前檢查輸入值。 這裏是代碼片段:https://jsbin.com/guduwakeji/edit?html,js,output應用驗證表單字段客戶端與角

var app = angular.module('myApp', []); 
 
app.controller('formCtrl', function($scope) { 
 
    $scope.ele = []; 
 
    $scope.updateDetails = function(ele) { 
 
    if (!ele.firstname && !ele.lastname) { 
 
     alert("Ele cannot be empty"); 
 
    } else { 
 
     ele.push({ 
 
     'firstname': '', 
 
     'lastname': '' 
 
     }); 
 
     alert(ele.firstname + " " + ele.lastname); 
 
    } 
 
    console.log(ele); 
 
    }; 
 

 
});
<!DOCTYPE html> 
 
<html> 
 

 
<head> 
 
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
    <meta charset="utf-8"> 
 
    <meta name="viewport" content="width=device-width"> 
 
    <title>JS Bin</title> 
 
</head> 
 

 
<body ng-app="myApp"> 
 
    <div ng-controller="formCtrl"> 
 
    <div> 
 
     First Name: 
 
     <input type="text" ng-model="ele.firstname"> 
 
     </br> 
 
     Last Name: 
 
     <input type="text" ng-model="ele.lastname"> 
 
     <br/> 
 
     <input type="button" value="Submit" ng-click="updateDetails(ele)"> 
 
    </div> 
 
    </div> 
 
</body> 
 

 
</html>

+0

請添加有問題的代碼本身。 –

+0

使用'ng-pristine','ng-dirty','ng-valid','ng-invalid' –

回答

0

使用此代碼

我這樣弄清楚驗證表單

var app = angular.module('myApp', []); 
app.controller('formCtrl', function($scope) { 
    $scope.ele={}; 
    $scope.updateDetails = function(ele){ 
    if(ele.firstname && ele.lastname) 
    { console.log(ele);} 
     else{ 
     alert("empty field not allowed"); 
     } 
    }; 

}); 
+0

是的,這也適用於我。謝謝。但是我有這個疑問,我們也可以在輸入字段中使用必需的屬性嗎?隨着模型驗證。 –

+0

它不工作,因爲它不是所需的HTML表單只能與HTML表單工作希望你得到它 – uzaif