我使用 ng-messages 编写了一个自定义验证。例如这里是一个大于验证:
(function (module) {
module.directive('greaterThanValidator', function () {
return {
require: ['ngModel'],
link: function (scope, element, attrs, ngModel) {
var data = attrs.greaterThanValidator;
ngModel.$validators.greaterThan = function (value) {
if (!isNaN(parseFloat(value)) && !isNaN(parseFloat(data))) {
value = parseFloat(value);
data = parseFloat(data);
}
if (!value || value.length == 0) {
element.$setValidity('greaterThan', true);
} else if (value>data) {
element.$setValidity('greaterThan', true);
} else {
element.$setValidity('greaterThan', false);
}
};
}
}
}
);
})(angular.module("lego.base"));
这是我的消息div
:
<div class="error-messages" ng-if="..."
ng-messages="form.field.$error">
<div ng-message="greaterThan">Your value should be greater than {{number}}</div>
</div>
如何传递number
to 消息内容?
Edit:
用法如下:
<input ng-model="something" greater-than-validator="100">