ng-required属性有助于根据条件生成所需的字段:
<input ... ng-required="object.isRequired" \>
但是如何将这种类型的使用扩展到使用我自己的自定义验证指令?例如,假设我有自定义验证fieldsMatch。现在我想基于属性“object.needsToMatch”将此验证添加到输入字段。我希望会有类似的东西:
<input ... fieldsMatch="object.needsToMatch"
如果解决方案是创建另一个处理条件的指令,那么如何将其替换为内联(在input元素中)?
次要问题:然后,当自定义验证采用属性时(如在fieldsMatch验证器的情况下,该字段需要与之匹配的模型字段),如何使其工作。
答案 0 :(得分:1)
我会创建一个指令来处理限制属性的指令。
<input ... ng-model="inputModel" fieldMatchValidator fieldToMatch="object.needsToMatch" />
并在指令中:
...directive('field-match-validator', function(){
require: 'ngModel',
scope:{
fieldToMatch: '='
},
link: function(scope, element, attrs, ngModelCtrl){
//watch on the model and validate it against scope.fieldToMatch
}
});
显然这有些粗糙,但应该让你开始。