为简化表单验证,我尝试从此处开始:
<div ng-class="{'field--error': form.firstname.$error.maxlength && form.firstname.$dirty}" class="field">
<label for="firstname" class="field__label">Firstname</label>
<input id="firstname" type="text" name="firsname" ng-model="formData.firstname" ng-maxlength="32" class="field__input">
</div>
到此:
<div field-error="{fieldName: 'firsname'}" class="field">
<label for="firstname" class="field__label">Firstname</label>
<input id="firstname" type="text" name="firsname" ng-model="formData.firstname" ng-maxlength="32" class="field__input">
</div>
我使用了fieldError指令来简化验证(特别是脏和触摸)。该指令通过'^ form'参数获取对formController的引用:
.directive('fieldError', function fieldError(){
return {
restrict: 'A',
require: '^form',
scope: {
fieldError: '='
},
link: function( scope, elem, attrs, formCtrl ) {
var
fieldInput = formCtrl[ scope.fieldError.fieldName ],
isInError = false;
if ( fieldInput && fieldInput.$dirty ) {
// validation process goes here
}
if ( isInError ) {
elem.addClass('field--error');
} else {
elem.removeClass('field--error');
}
}
};
})
问题:在输入中键入文本时,不会调用链接函数。 也许我必须使用观察者,但我听说这是不好的做法。
修改
在post之后我更新了我的指令:
link: function( scope, elem, attrs, formCtrl ) {
var fieldInputPath = formCtrl.$name + '.' + scope.fieldError.fieldName + '.$invalid';
// fieldInputPath = 'form.firstname.$invalid'
scope.$watch( fieldInputPath, function( n, o ) {
// never fired
} );
}
但观察者从未被解雇过。我在devtool中放了一个断点,fieldInputPath很好。
有什么想法吗?