且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在angularjs中将表单设置为无效

更新时间:2023-02-25 12:21:02

经过研究后,以下代码对我来说很好用.在控制器中:

//Set the form as invalid for start.
  $timeout(function(){
   $scope.orderForm.productsForm.$invalid = true;
  });

超时确保我们可以访问该表单.它们不是在第一次通过控制器上构建的,因此需要超时或监视. 然后,我们将表单标记为无效.更好的方法是使用ngModelController上已记录的api $setValidity定位可以标记为无效的输入,但是在我的用例中,尚无输入,因此我们以一种肮脏的方式进行输入.

一个警告是,当直接像在相应的$ invalid ===上方那样进行设置时! $ valid不变量已损坏,因此请谨慎使用此hack.

I need to set ng-form as invalid in the start, as it is a later part of a wizard. The form contains a grid with elements. Each element has its own validation, but the issue is that when there are no elements the form shows as valid. I need to mark it as invalid for the start case when the number of rows is 0. How can one do it?

After some research the following code works fine for me. In the controller:

//Set the form as invalid for start.
  $timeout(function(){
   $scope.orderForm.productsForm.$invalid = true;
  });

The timeout assures that we gain access to the form. They are not constructed on the first pass through controller so a timeout or watch is needed. Then we mark form as invalid. A better way could be locating an input that we can mark as invalid using documented api $setValidity on ngModelController, but in my use case there is no input yet so we do it in a dirty way.

One caveat is that when one sets this directly like above the corresponding $invalid === ! $valid invariant is broken, so be careful with this hack.