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

标签 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();
    }
}

我的字段循环基于 this solution ,我已经读过 this question几次。 似乎首选的解决方案是创建一个指令,但向每个表单元素添加一个指令似乎有点矫枉过正。

是否有更好的方法通过指令来解决这个问题?

最佳答案

指令代码:

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();
                }
            });
        })
    }
}
});

Controller 中使用的工厂:

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

示例 Controller :

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

关于angularjs - 将焦点设置到 AngularJS 中的第一个无效表单元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19849174/

相关文章:

javascript - 将值传递给 AngularJS 单击事件

angularjs - Golang 和 AngularJS 模板冲突

android - 在 Cordova 中提交表单

angularjs - 在 AngularJS 中渲染嵌套对象时更改范围

AngularJs http请求优先级和http拦截器

javascript - Angular : Return a promise which is constructed from the result of another promise in angular?

angularjs - 如何使用 jqLit​​e 按类名选择元素?

javascript - 如果其主页在 angularJS 中,则添加类

android - ng click 不调用函数——对 angular 和 ionic 来说非常新

angularjs - 如何突出显示当前菜单项?