[英]How to write a generic error handler for AngularJS Forms
這是該問題的后續提問:
因此,使用該答案,您可以在模板中編寫一些HTML,該模板將顯示給您給$ setValidity的每個錯誤的特定錯誤。 例如,這是一個:
<input ng-model="user.lastName" required="true" id="lastNameField" name="lastName" type="text" class="span3" placeholder="Last Name"/>
<span class="inlineError" ng-show="myProfile.lastName.$error.required">Required</span>
但是,如果我想為姓氏添加一個字符,且其長度必須為4個或更多字符,則需要:
<input ng-model="user.lastName" required="true" id="lastNameField" name="lastName" type="text" class="span3" placeholder="Last Name"/>
<span class="inlineError" ng-show="myProfile.lastName.$error.minRequired">Last name must be at least 4 characters long</span>
我的問題是如何為字段中的所有錯誤編寫通用處理程序。 就像是:
<input ng-model="user.lastName" required="true" id="lastNameField" name="lastName" type="text" class="span3" placeholder="Last Name"/>
<span class="inlineError" ng-show="myProfile.lastName.$error.required">{{myProfile.lastName.$error.required}}</span>
那可能嗎?
您是說您只想表明表單元素的有效性嗎? 然后,您可以執行以下操作:
<span ng-show="myProfile.lastName.$invalid">Input field is invalid.</span>
如果需要更具體,則可以使用ng-repeat
遍歷myProfile.lastName.$error
對象並顯示所有錯誤。 在這種情況下,您必須具有一些錯誤名稱才能將錯誤消息轉換為可讀性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.