简体   繁体   English

AngularJS-具有多个实例的控制器的表单验证

[英]AngularJS - Form validation for a controller with multiple instances

My requirements 我的要求

I have business requirements that make it necessary to do manual validation because the validation rules would be less or more strict, depending on the context in which you will enter a specific screen. 我有一些业务需求,因此有必要进行手动验证,因为验证规则会变得更严格或更严格,具体取决于您要进入特定屏幕的上下文。

Also, it is possible that multiple instances of the same view (and as a result, the same controller) are loaded simultaneously. 同样,可能同时加载同一视图的多个实例(因此,同一控制器)。

Current attempt 当前尝试

Consider this Plunkr : 考虑一下这个Plunkr

It uses the following function to do validation: 它使用以下功能进行验证:

self.SaveAndValidate = function(validationContext){
  var validationRules = self.GetValidationContext(validationContext);

  self.RemoveAllClassInfo();

  angular.forEach(validationRules, function(value){
    $('#' + value.Field).addClass('mandatory');
  })
}

As you will notice you can save for a different context, which will result in different fields being indicated as mandatory. 如您所见,您可以保存其他上下文,这将导致不同的字段被指示为必填字段。

The question 问题

As you will notice clicking the buttons of the second form doesn't work as expected, because they are targeting the first form, not the second. 如您所见,单击第二个表单的按钮无法正常工作,因为它们的目标是第一个表单,而不是第二个。 And that makes sense, because I'm using jQuery to target the input fields using specific field names. 这很有意义,因为我正在使用jQuery使用特定字段名称来定位输入字段。 In this case, they exist twice on the same page, so the first occurrence is targeted. 在这种情况下,它们在同一页面上存在两次,因此首次出现是有针对性的。

  • How can I change this so that each validation targets the correct form? 如何更改此设置,以便每个验证都针对正确的表单?
  • Is there a way to do this with Angular, rather than jQuery? 有没有办法用Angular而不是jQuery来做到这一点?

You ought to rethink your way of adding the mandatory class. 您应该重新考虑添加强制类的方式。 Maybe create a custom directive, or simply a ng-class={'mandatory' : isMandatory(yourId) } where isMandatory(id) iterates over your list to decide if it's a mandatory field. 也许创建一个自定义指令,或者简单地创建一个ng-class = {'mandatory':isMandatory(yourId)},其中isMandatory(id)遍历您的列表以决定它是否为必填字段。

Otherwise the Best practice would be to take a look at ng-form and use the ng-invalid ng-touched classes. 否则,最佳实践将是查看ng-form并使用ng-valid ng-touched类。 https://docs.angularjs.org/guide/forms https://docs.angularjs.org/guide/forms

And finaly, please don't use JQuery in your angularJS controller. 最后,请不要在您的angularJS控制器中使用JQuery。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM