2016-12-24 28 views
-2

我的問題是關於處理大型Angular應用程序的客戶端驗證。我有一個包含不同組件的大型SPA應用程序,其中包含可重複使用的組件,如zip控件。現在我可以將這些組件集成到我的頁面表單中,但是如何觸發組件中駐留元素的驗證。對於例如我的zip組件有城市輸入框,狀態選擇框和zip輸入框,現在我怎樣才能從表單提交中觸發這些組件的驗證?從主頁上的表單驗證指令元素

+0

你有什麼到目前爲止已經試過? –

回答

0

我現在正在爲我的應用程序使用以下解決方案。我能夠使用此解決方案驗證必填字段。

我在指令中創建了兩個輸入字段,並在表單中創建了兩個輸入字段。我能夠顯示兩個字段的錯誤消息。同樣,這可以用於其他一些驗證形式。

這裏是我的plunker https://plnkr.co/edit/laW9jYoNCszHlPeIl3Vs?p=preview

的script.js

var app = angular.module('validationModule', []); 
app.controller('mainCtrl', mainCtrl); 
app.directive('testDirective', testDirective); 

function testDirective(){ 
    var testDirective = { 
    template: 'First Name: <input type="text" name="fName" required ng-model="user.firstName">' 
    }; 

    return testDirective; 
} 

mainCtrl.$inject = ['$scope']; 

function mainCtrl($scope){ 
    $scope.submitForm = function(user){ 
    alert(user.firstName + " " + user.lastName); 
    } 
} 

index.html文件

<!DOCTYPE html> 
<html ng-app="validationModule"> 

<head> 
    <meta charset="utf-8" /> 
    <title>AngularJS Plunker</title> 
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.9/angular.js" charset="UTF-8"></script> 
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.9/angular-animate.js" charset="UTF-8"></script> 
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.9/angular-sanitize.js" charset="UTF-8"></script> 
    <script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-2.3.1.js" charset="UTF-8"></script> 
    <link href="//netdna.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"> 
    <script src="script.js"></script> 
</head> 

<body ng-controller="mainCtrl"> 
    <form name="myForm" ng-submit="myForm.$valid? submitForm(user) : ''" novalidate> 
    <h1>Input User Name</h1><br/> 
    <test-directive></test-directive><br/> 
    Last Name: <input type="text" name="lName" required ng-model="user.lastName"> 
    <button type="submit" class="btn btn-danger">Submit</button> 

    <div class="alert alert-danger" ng-show="myForm.$submitted"> 
     <div ng-show="myForm.fName.$error.required"> 
     First Name is required 
     </div> 
     <div ng-show="myForm.lName.$error.required"> 
     Last Name is required 
     </div> 
    </div> 

    <br/><br/><br/> 
    <h1>Is form valid? {{myForm.$valid}}</h1> 
    </form> 
</body> 

</html>