我寫的完成了很多鍋爐板工具和驗證一個指令。它包括允許默認消息:
angular.module('validations').directive('showErrors', function() {
return {
restrict: 'A',
require: '^form',
link: function(scope, el, attrs, ngModelCtrl) {
var data = el.data();
var inputName = el.attr('name');
if (!inputName)
return;
var baseFormName = ngModelCtrl.$name;
var baseFieldName = baseFormName + '.' + inputName + '.$error.';
var validationMessages = '';
var validators = {};
var defaultValidationConditions = [];
var defaultValidationMessage = '';
angular.forEach(data, function (value, key) {
if (key.indexOf('se') === 0 && key[2] === key[2].toUpperCase()) {
var validationProperty = key.substring(2).toLowerCase();
// if this is the default message, just grab it and keep looping.
if (validationProperty === 'default') {
defaultValidationMessage = value;
return;
}
var condition = baseFieldName + validationProperty;
if (!validators[value]) {
validators[value] = [];
}
validators[value].push(condition);
// if we have a message for this error, we want to exclude it from the default
defaultValidationConditions.push('!' + condition);
}
});
defaultValidationConditions.push([baseFormName, '.', inputName, '.$invalid'].join(''));
angular.forEach(validators, function (conditions, message) {
var conditionString = conditions.join(' || ');
validationMessages += '<label ng-show="' + conditionString + '" class="error">' + message + '</label>';
});
// if a default validation message was specified, we need to create a label
if (defaultValidationMessage) {
validationMessages += '<label ng-show="' + defaultValidationConditions.join(' && ') + '" class="error">' + defaultValidationMessage + '</label>';
}
if (validationMessages) {
el.after(this.$compile('<div ng-show="' + baseFormName + '.' + inputName + '.$dirty">' + validationMessages + '</div>')(scope));
}
}
}
});
這是非常簡單的使用方法:
<form name="myForm">
<input show-errors data-se-required="Field required"
data-se-default="Field Invalid"
name="myInput" ng-minlength="10" required />
</form>
該指令會自動生成所有的HTML。它使用div和標籤,但可以根據需要調整爲使用ngMessages。 JSFiddle目前有點不習慣。我會盡量在明天添加一個工作鏈接。
來源
2015-10-26 02:31:26
Bic
不確定一般的解決方案,但數字上的大多數錯誤都屬於'$ error.number'屬性。 – ryanyuyu