我想为Angular的ngMessages添加一个自定义验证函数。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;
};
}
};
非常感谢您的详细回复。我可能正在尝试在这里推动角度验证。我会看看你链接的资源,看看什么最适合我的用例。再次感谢! – Mac