我正在尝试向 Angular 的 ngMessages 添加自定义验证功能。
具体来说,我希望几个输入的值(输入的数量是动态的,但现在坚持使用 2)总计 100。
我创建了一个名为的新指令totalOneHundred
,它触发表单更改,但我无法弄清楚如何从link:
回调中访问其他表单值。
我在下面发布了我的代码。有什么我想念的吗?此外,如果有更好的方法来实现这一点(例如sum()
,控制器中的一个函数和一个ng-show
),请给我打电话。
谢谢你的帮助。
表格:
<!-- input box to be validated -->
<input type="number" class="form-control" name="lowBound" ng-model="ctrl.lowBound" total-one-hundred required>
<!-- validation messages -->
<div ng-messages="form['lowBound'].$error" role="alert">
<div ng-message="required">Cannot be empty</div>
<div ng-message="totalOneHundred">Sum of tasks must = 100</div>
</div>
<!-- input box to be validated -->
<input type="number" class="form-control" name="highBound" ng-model="ctrl.highBound" total-one-hundred required>
<!-- validation messages -->
<div ng-messages="form['highBound'].$error" role="alert">
<div ng-message="required">Cannot be empty</div>
<div ng-message="totalOneHundred">Sum of tasks must = 100</div>
</div>
指令:
return {
restrict: "A",
require: ["^^form", "ngModel"],
link: function(scope, element, attributes, controllers) {
// At first, form is assigned the actual form controller...
const form = controllers[0];
const model = controllers[1];
model.$validators.totalOneHundred = function (modelValue, form, element, scope) {
// however, the value of form here is "1".
// modelValue is the value of the triggering input,
// but how can I access the other form inputs?
return true;
};
}
};