Question: How to programmatically set focus, and optionally select text?
What do you mean with optionally select text? Can you give more info of this use case?
I thought it like a input text box; when focused also select all text so that user can replace it with another entry. So, it seems not applicable to ui-select?
For now, I managed to set focus on ui-select, inside my own focusing directive like below:
if (elem.hasClass('ui-select-bootstrap')) { if (elem[0].children.length === 4) { $timeout(function () { elem[0].children[3].focus(); }, 0); } }
@synergetic Can you share the directive?
Okay this is what I came up with, based on @synergetic's code:
.directive("autofocus", ($timeout) ->
{
restrict: 'A'
require: 'uiSelect'
link: (scope, elem, attr) ->
if elem.hasClass('ui-select-bootstrap')
if elem[0].children.length == 4
$timeout(->
if attr.autofocus == 'open'
elem.find("button.ui-select-match").click()
elem.find("input.ui-select-focusser").focus()
0);
}
)
Usage:
<ui-select autofocus>...</ui-select> automatically focusses the element, you can start typing, but the list of NOT expanded initially.
<ui-select autofocus="open"> opens the dropdown (list is expanded) and focusses the input, so you can start typing / searching.
Note: I only tested it in Chrome, Angular 1.3.0, with bootstrap theme, so it may or may not work.
Thanks for sharing, this is awesome!
I had no luck with the above directive. It seems the number of children in the ui-select node has changed in the later versions of ui-select and there is no button.ui-select-match. Here it is a simpler directive inspired by the above one:
app.directive("uiselectAutofocus", function ($timeout) {
return {
restrict: 'A',
require: 'uiSelect',
link: function (scope, elem, attr) {
$timeout(function() {
var input = elem.find('input');
if (attr.uiselectAutofocus == 'open')
input.click();
input.focus()
}, 0);
}
}
});
The idea is to find the first input and focus it. Usage:
<ui-select uiselect-autofocus>...</ui-select>
and for visible choices:
<ui-select uiselect-autofocus="open">...</ui-select>
Any thoughts on how to not auto focus, but rather gain focus in one's JS code at a certain point in the program flow, e.g. after the user completes some action on the page?
Cleaner way:
yourModule.directive('uiSelectOpened', function($timeout) {
return {
restrict: 'A',
require: 'uiSelect',
link: function(scope, element, attrs, uiSelect) {
$timeout(()=> uiSelect.toggle())
}
};
});
<ui-select ... autofocus="true" ui-select-opened>...</ui-select>