【问题标题】:Focus on the first field that is .ng-invalid at Submit - not working for radios-inline关注提交时 .ng-invalid 的第一个字段 - 不适用于 radios-inline
【发布时间】:2015-11-24 22:00:30
【问题描述】:

我正在使用Set focus on first invalid input in AngularJs form 上接受的答案中的指令来完成此操作:

app.directive('accessibleForm', function () {
    return {
        restrict: 'A',
        link: function (scope, elem) {

            // set up event handler on the form element
            elem.on('submit', function () {

                console.log("inside focus directive");
                // find the first invalid element
                var firstInvalid = elem[0].querySelector('.ng-invalid');
                //if we find one, set focus
                if (firstInvalid) {
                    firstInvalid.focus();
                }
            });
        }
    };
});

只要我不使用 radios-inline,焦点就可以工作。请参考:http://jsfiddle.net/mutharasus/mu7y4k8f/

但是,如果第一个错误发生在 radios-inline 字段上,则焦点不起作用。请参考:http://jsfiddle.net/mutharasus/00jzbL6g/

我不确定如何解决。请帮忙。

【问题讨论】:

    标签: angularjs angular-schema-form


    【解决方案1】:

    radio-inline 正在将 ng-invalid 类添加到字段标签,而不是添加到每个单独的无线电输入。

    您可以更改该指令并在您的自定义指令中实现您想要的行为(您需要将 ng-invalid 添加到每个无线电输入)或更改 accessibleForm 指令以检查无效元素是否为标签,并且在这种情况下,找到与之关联的第一个无线电输入:

    app.directive('accessibleForm', function () {
        return {
            restrict: 'A',
            link: function (scope, elem) {
    
                // set up event handler on the form element
                elem.on('submit', function () {
    
                    console.log("inside focus directive");
    
                    // find the first invalid element
                    var firstInvalid = elem[0].querySelector('.ng-invalid');
    
                    // If we got a label, then it is a radio-inline
                    if(firstInvalid && firstInvalid.tagName === 'LABEL') {
                        firstInvalid =  elem[0].querySelector('.ng-invalid + div input[type=radio]')
                    }
    
                    firstInvalid && firstInvalid.focus();
    
                });
            }
        };
    });
    

    虽然这似乎是最简单的解决方案,但对我来说,第二个查询选择器在很大程度上取决于该特定指令的结构,好像它发生了变化,那么 accessibleForm 指令将被破坏再次。

    【讨论】:

    • 此解决方案有效!谢谢。我会在我在 github 存储库中创建的问题中记录您的评论
    【解决方案2】:

    我认为问题在于每个收音机的标签都有“.ng-invalid”类,但收音机输入元素本身没有,无论如何都会出现。您的查询选择器无意中返回标签的元素,然后在其上无用地调用 focus()'。

    这是在单选无效时调用焦点的元素:

    <label ng-model="model['Field1']" ng-model-options="form.ngModelOptions" schema-validate="form" class="control-label  ng-valid-schema-form ng-dirty ng-invalid ng-invalid-tv4-302" ng-show="showTitle()">Field1</label>
    

    其他类型控件的标签没有 .ng-invalid 类,因此它们不会受到这个问题的困扰。

    我不熟悉这些库,所以答案取决于。要么改进选择器,要么改变单选输入标签的样式。

    Here's a version of the jsFiddle 我已经破解以证明它是阻止焦点发生的选择器。只需点击提交,无需更改表单。

    【讨论】:

      猜你喜欢
      • 2017-01-07
      • 2014-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-21
      • 1970-01-01
      相关资源
      最近更新 更多