Skip to content

Instantly share code, notes, and snippets.

@tolemac
Last active August 29, 2015 14:26
Show Gist options
  • Save tolemac/7fdaa62416da6561de35 to your computer and use it in GitHub Desktop.
Save tolemac/7fdaa62416da6561de35 to your computer and use it in GitHub Desktop.
To do work angular-focus-manager with md-autocomplete (from Angular Material)
module LoB.Directives {
window.LoBModule.directive("lobAutocompleteAutofocus", ["focusManager", "focusQuery", (focusManager, focusQuery) => {
var focusEls = [];
var focusElsCount = 0;
var unwatchChanges: Function;
var timer: number;
function reset() {
unwatchChanges = null;
focusElsCount = 0;
clearInterval(timer);
}
return {
restrict: "A",
require: "mdAutocomplete",
scope: false,
link(scope, element, attr, mdAutocompleteCtrl) {
var unWatch = scope.$watch(() => {
var input = $("input[name='" + mdAutocompleteCtrl.scope.inputName + "']", element);
return input.length;
},(value, oldValue) => {
if (value !== oldValue && value > 0) {
// desactivamos el watch
unWatch();
var inputElement = $("input[name='" + mdAutocompleteCtrl.scope.inputName + "']", element);
// Copy from autofocus directive of angular-focus-manager
var el = inputElement[0];
var focusIndex = !attr.lobAutocompleteAutofocus ? 0 : parseInt(attr.lobAutocompleteAutofocus, 10);
focusEls[focusIndex] = el;
focusElsCount += 1;
if (!unwatchChanges) {
unwatchChanges = scope.$watch(() => {
unwatchChanges();
var tries = 0, maxTries = 1e3;
timer = setInterval(() => {
if (tries < maxTries) {
var len = focusEls.length;
for (var i = 0; i < len; i += 1) {
el = focusEls[i];
if (focusQuery.isVisible(el)) {
reset();
focusManager.focus(el);
el.focus();
break;
}
}
tries += 1;
} else { }
}, 10);
});
}
scope.$on("$destroy",() => {
reset();
});
///////
}
});
}
};
}]);
window.LoBModule.directive("lobAutocompleteFocusIndex",() => {
return {
restrict: "A",
require: "mdAutocomplete",
scope: false,
link: (scope, element, attrs:any, mdAutocompleteCtrl) => {
var unWatch = scope.$watch(() => {
var input = $("input[name='" + mdAutocompleteCtrl.scope.inputName + "']", element);
return input.length;
},(value, oldValue) => {
if (value !== oldValue && value > 0) {
var input = $("input[name='" + mdAutocompleteCtrl.scope.inputName + "']", element);
input.attr("focus-index", !attrs.lobAutocompleteFocusIndex ? 0 : parseInt(attrs.lobAutocompleteFocusIndex, 10));
unWatch();
}
});
}
};
});
}
@tolemac
Copy link
Author

tolemac commented Aug 7, 2015

About angular-focus-manager: http://obogo.github.io/angular-focusmanager/

You cannot access to md-autocomplete internal input until your page is running, these directives allow you use angular-focus-managerfeatures.

You can use lob-autocomplete-autofocus attribute in your md-autocomplete html tags.
And also can use lob-autocomplete-focus-index attribute.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment