我試圖將Bootstrap表單驗證顯示與AngularJS驗證模型聯合起來。使用Bootstrap和AngularJS進行表單驗證
- 如果用戶加載一個空表單,我不希望表單立即顯示錯誤信息。我想等到用戶與表單交互。
- 如果用戶提交的表單中未填寫必填字段,我還想顯示一條錯誤消息。
- 如果用戶開始在該字段中輸入內容,我想要立即顯示錯誤消息。
所以我必須檢查myForm.$submitted
,myForm.<fieldName>.$dirty
以及myForm.<fieldName>.$touched
。
但是,它使很多重複的代碼變化很少。
我試圖做一個指令來解決這個問題,但我似乎無法找到正確的方式來包裝這種複雜性。
HTML:
<div class="form-group required" ng-class="{ 'has-error': myForm.firstname.$invalid && (myForm.firstname.$dirty || myForm.$submitted || myForm.firstname.$touched) }">
<label for="firstname" class="control-label" translate>Profile.FirstName</label>
<input type="text" class="form-control" id="firstname" name="firstname" required ng-model="vm.profile.firstName"/>
<p class="help-block" ng-if="myForm.firstname.$error.required" translate>Forms.Default.Required</p>
</div>
我想取整ng-class
屬性,並通過更多的東西簡潔取代它。該指令似乎是要走的路,從而嘗試這樣做:
(function(){
'use strict';
angular.module('app')
.directive('hasError', [function(){
return {
restrict: 'A',
scope: {
form: '=bsForm',
control: '=bsControl'
},
link: function(scope, element){
scope.$watch('form', function(){
var isInvalid = scope.control.$invalid && scope.control.$dirty;
element.toggleClass('has-error', isInvalid);
});
}
};
}]);
})();
用法:
<div class="form-group required" has-error bs-form="myForm" bs-control="myForm.firstname">
...
</div>
這時候的form
性質改變但並沒有讓人耳目一新。
我缺少什麼?