将焦点设置为AngularJS中的第一个无效表单元素



基本上,我要完成的是,在尝试提交表单后将焦点设置为第一个无效元素。此时,我已将元素标记为无效,并且可以获取该元素的$name,以便我知道它是哪一个。

它正在"工作",但抛出"$apply正在进行中"错误......
所以我一定在这里做错了什么:)

这是我到目前为止的代码:

$scope.submit = function () {
    if ($scope.formName.$valid) {
        // Good job.
    }
    else 
    {
        var field = null,
            firstError = null;
        for (field in $scope.formName) {
            if (field[0] != '$')
            {
                if (firstError === null && !$scope.formName[field].$valid) {
                    firstError = $scope.formName[field].$name;
                }
                if ($scope.formName[field].$pristine) {
                    $scope.formName[field].$dirty = true;
                }
            }
        }
        formName[firstError].focus();
    }
}

我的字段循环基于此解决方案,我已经多次阅读了这个问题。似乎首选的解决方案是创建一个指令,但是为每个表单元素添加一个指令似乎有点矫枉过正。

有没有更好的方法来用指令解决这个问题?

指令代码:

app.directive('ngFocus', function ($timeout, $log) {
return {
    restrict: 'A',
    link: function (scope, elem, attr) {
        scope.$on('focusOn', function (e, name) {
            // The timeout lets the digest / DOM cycle run before attempting to set focus
            $timeout(function () {
                if (name === attr.ngFocusId) {
                    if (attr.ngFocusMethod === "click")
                        angular.element(elem[0]).click();
                    else
                        angular.element(elem[0]).focus();
                }
            });
        })
    }
}
});

在控制器中使用的工厂:

app.factory('focus', function ($rootScope, $timeout) {
    return function (name) {
        $timeout(function () {
            $rootScope.$broadcast('focusOn', name);
        }, 0, false);
    };
});

示例控制器:

angular.module('test', []).controller('myCtrl', ['focus', function(focus) {
  focus('myElement');
}

构建指令绝对是要走的路。否则,在angularjs中选择元素没有干净的方法。它只是不是这样设计的。我建议您查看有关此问题的此问题。

您不必为每个表单元素创建一个指令。每个表单的 On 就足够了。在指令中,您可以使用element.find('input'); .对于焦点本身,我想你需要包含jQuery并使用它的focus函数。

你可以直接在控制器中使用jQuery,我不会推荐这样做。通常角度表单验证会添加诸如ng-invalid-required之类的类,您可以将其用作选择器。例如:

$('input.ng-valid').focus();

根据雨果的反馈,我设法整理出一条指令:

.directive( 'mySubmitDirty', function () {
    return {
        scope: true,
        link: function (scope, element, attrs) {
            var form = scope[attrs.name];
            element.bind('submit', function(event) {
                var field = null;
                for (field in form) {
                    if (form[field].hasOwnProperty('$pristine') && form[field].$pristine) {
                        form[field].$dirty = true;
                    }
                }
                var invalid_elements = element.find('.ng-invalid');
                if (invalid_elements.length > 0)
                {
                   invalid_elements[0].focus();
                }
                event.stopPropagation();
                event.preventDefault();
            });
        }
    };
})

这种方法需要 jquery,因为element.find()使用类来查找 dom 中的第一个无效元素。

最新更新