gpt4 book ai didi

javascript - 输入永远不会从 Angular 获取 ng-invalid-class

转载 作者:行者123 更新时间:2023-11-27 22:35:21 24 4
gpt4 key购买 nike

我们通过额外指令为自定义表单元素注册自定义验证方法:

<ng-form name="validatorTestForm">
<our-input-directive name="validatorTest"
ng-model="ourModel"/>
</our-input-directive>
<our-validator-directive name="validatorTest"
form="validatorTestForm"
ng-model="ourModel">
</our-validator-directive>
</ng-form>

它通过属性获取所有信息,以了解以哪种形式验证哪个输入;然后我们通过启动指令来连接它:(精简版本)

registerValidator(ourModel.form, 'validatorTest');

function registerValidator(form, inputName) {
var validationModel = form[inputName];

validationModel.$validators.testValidator = function (modelValue) {
// validate to true when there are more then two characters entered
return modelValue.length > 2;
};
}

our-input-directive 非常简单:

angular.directive('ourInputDirective', function() {
return {
restrict: 'E',
template: '<input type="text" ng-model="model">',
scope: {
model: '=?ngModel'
}
}
});

所以我们运行它,Angular 发挥了它的魔力,并在我们输入某些内容时向表单元素和输入元素添加了大量的 css 类。输入中,它正确触发了验证。当表单元素有效时,它会得到一个 css-class 'ng-valid';当它无效时,它会得到一个 'ng-invalid'。

输入的内容只有“ng-valid”类并且永远不会变得无效!
那么为什么会这样,我该如何更改它,以反射(reflect)输入 css 类上的模型更改?


我们希望利用“ng-invalid”类来更改输入的样式。

最佳答案

使用 ng-model https://docs.angularjs.org/api/ng/directive/ngModel

ngModel is responsible for:

  • Binding the view into the model, which other directives such as input, textarea or select require.
  • Providing validation behavior (i.e. required, number, email, url).
  • Keeping the state of the control (valid/invalid, dirty/pristine, touched/untouched, validation errors).
  • Setting related css classes on the element (ng-valid, ng-invalid, ng-dirty, ng-pristine, ng-touched, ng-untouched, ng-empty, ng-not-empty) including animations.
  • Registering the control with its parent form.

这是您的工作方式的工作原理。 https://plnkr.co/edit/yWlZln2TekdCAhrZ6iEG?p=preview

function customValidator() {
var directive = {
require: '^form',
link: link
};
return directive;

function link(scope, element, attrs, formCtrl) {
modelCtrl = formCtrl[attrs['name']];
modelCtrl.$validators.testValidator = function (modelValue, viewValue) {
var value = modelValue || viewValue;
if(modelCtrl.$isEmpty(value)){
return false;
}
return value.length > 2;
};
}
}

关于javascript - 输入永远不会从 Angular 获取 ng-invalid-class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39163243/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com