So, I have the following Angular directive to autofocus first input
field on the current page of my Ionic application. It works great when the first field isn't hidden. But, if it's hidden by ng-hide
, logic fails. So need to modify the element selector to find just for visible elements in my directive.
所以,我有以下的角指令自动聚焦在我的离子应用的当前页上的第一个输入域。当第一个字段不被隐藏时,它工作得很好。但是,如果它被ng隐藏,逻辑就失败了。所以需要修改元素选择器来找到我的指令中可见的元素。
angular.module('myApp').directive('focusMe', function($timeout) {
return {
link: function(scope, element, attrs) {
$timeout(function() {
element.find('label')[0].focus();
}, 150);
}
};
});
Using above directive on a form
element as follows,
在表单元素上使用上述指令,如下所示,
<form name="signinForm" ng-submit="signinForm.$valid && doSignin(credentials)" novalidate focus-me>
So how should I change my jQLite find query to just look for the visible element? The find lookup is limited by tag name as per docs.
那么,我应该如何更改jQLite查找查询以只查找可见元素呢?查找按文档中的标记名进行限制。
1 个解决方案
#1
2
You can write something like this:
你可以这样写:
element[0].querySelector('input:not(.ng-hide)').focus();
jQLite only allows selecting by tag name. So we can use the pure Javascript version i.e. querySelector
along with using :not
selector.
jQLite只允许按标记名进行选择。所以我们可以使用纯Javascript版本即querySelector以及using:not selector。
See a working example below:
参见下面的一个工作示例:
angular.module('myApp', [])
.directive('focusMe', function($timeout) {
return {
link: function(scope, element, attrs) {
$timeout(function() {
element[0].querySelector('input:not(.ng-hide)').focus();
}, 150);
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<form focus-me ng-app="myApp">
<input type="text" name="firstName" ng-show="false" />
<input type="text" name="lastName" ng-show="true" />
<input type="text" name="email" />
</form>
#1
2
You can write something like this:
你可以这样写:
element[0].querySelector('input:not(.ng-hide)').focus();
jQLite only allows selecting by tag name. So we can use the pure Javascript version i.e. querySelector
along with using :not
selector.
jQLite只允许按标记名进行选择。所以我们可以使用纯Javascript版本即querySelector以及using:not selector。
See a working example below:
参见下面的一个工作示例:
angular.module('myApp', [])
.directive('focusMe', function($timeout) {
return {
link: function(scope, element, attrs) {
$timeout(function() {
element[0].querySelector('input:not(.ng-hide)').focus();
}, 150);
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<form focus-me ng-app="myApp">
<input type="text" name="firstName" ng-show="false" />
<input type="text" name="lastName" ng-show="true" />
<input type="text" name="email" />
</form>