基本上,我想要完成的任务是在尝试提交表单后将焦点设置到第一个无效元素。此时,我的元素被标记为无效,并且我可以获得$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();
}
}
我的字段循环基于这个解决方案 https://stackoverflow.com/questions/18324773/force-ng-dirty-in-angularjs-form-validation,我已经读过这个问题 https://stackoverflow.com/questions/14833326/how-to-set-focus-in-angularjs几次。它seems就像首选的解决方案是创建一个指令一样,但是向每个表单元素添加一个指令似乎有点矫枉过正。
有没有更好的方法通过指令来解决这个问题?
指令代码:
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');
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)