【问题标题】:Set required attribute for an input element if it's not hidden如果输入元素没有隐藏,则为它设置必需的属性
【发布时间】:2015-05-01 03:46:22
【问题描述】:

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

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

如果 condition() 返回 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>

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

【问题讨论】:

    标签: angularjs ng-show


    【解决方案1】:

    不要使用 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.
    

    【讨论】:

      【解决方案2】:

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

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

      在您的控制器中,您可以在 condition1() 和/或 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;
        }
      }
      

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

      【讨论】:

        【解决方案3】:

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

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

        【讨论】:

        • 使用 ng-if 代替 ng-show,这就是解决方案。见上文
        • @Artisan72 你检查过时间吗..当我添加答案时..比你早 3 分钟
        猜你喜欢
        • 2023-03-29
        • 2013-04-19
        • 1970-01-01
        • 1970-01-01
        • 2015-11-29
        • 2015-10-23
        • 1970-01-01
        • 2013-08-19
        • 2016-08-28
        相关资源
        最近更新 更多