如果未隐藏,则为输入元素设置必需属性

Set required attribute for an input element if it's not hidden

我正在使用 angular.js 处理动态表单。 输入字段

<div ng-show="condition()">
    <input type="text" name="field" required>
</div>

如果 condition() returns 为 false,则不会显示输入字段。 但是通过单击提交按钮,我将进入 chrome,消息:

An invalid form control with name='field' is not focusable.

好吧,一个解决方案是,使用 ng-required:

<div ng-show="condition()">
    <input type="text" name="field" ng-required="condition()">
</div>

好吧,这里我必须重复代码,多次使用 condition()。

它变得糟糕,当你可以封装 ng-show 的时候:

<div ng-show="condition1()">
    <div ng-show="condition2()">
        <input type="text" name="field"
            ng-required="condition1() && condition2()">
    </div>
</div>

有没有更好的方法,当输入可见时,所需的标签应该在那里,而不是,如果它是隐藏的。

我建议您需要使用 ng-if,这将从表单中删除元素,或者如果条件不满足,您可以说 DOM。你的代码会变成

<div>
    <div>
        <input type="text" name="field"
            ng-if="condition1() && condition2()" required>
    </div>
</div>

一种选择是使用变量而不是调用函数。

<div ng-show="condition1()">
<div ng-show="condition2()">
    <input type="text" name="field"
        ng-required="isRequired">
</div>

并且在您的控制器中,您可以在 condition1() and/or condition2() 函数中将 isRequired 变量设置为 true 或 false。

function myController($scope){
  $scope.isRequired = false;  // initialize it

  $scope.condition1 = condition1;
  $scope.condition2 = condition2;

  function condition1(){
    var returnValue = false;
    // Do some testing that sets returnValue true or false    
    $scope.isRequired = returnValue;
    return returnValue;
  }

  function condition2(){
    var returnValue = false;
    // Do some testing that sets returnValue true or false    
    $scope.isRequired = returnValue;
    return returnValue;
  }
}

显然这不是防弹代码。但这是一个开始。

不要使用 ng-show,而是使用 ng-if,因为当您使用 ng-show 时,该元素仍然是 DOM 的一部分。

像这样:

<div ng-if="condition()">
    <input type="text" name="field" required>
</div>

这样你就不会出错

An invalid form control with name='field' is not focusable.