I have this directive which sets focus on an input field when it appears and hides it when it loses focus or the esc/enter/tab key is pressed. It works just fine, but I wanted to know if there was a way I could pass in an array or object of keys (and event types) instead of hard coding the keys and events into the directive itself? Here is the code:
.directive('bindKeys', function ($timeout) {
return {
restrict: 'A',
scope: {
trigger: '='
},
link: function(scope, elem){
elem.bind('keydown keypress blur', function (event) {
if(event.which === 13 || event.which === 9 || event.which === 27 || event.type === 'blur') {
event.preventDefault();
$timeout(function(){
scope.trigger.property = false;
});
}
});
scope.$watch('trigger.property', function(value) {
if(value === true) {
$timeout(function() {
elem[0].focus();
});
}
});
}
};
});
The element looks like this:
<input bindKeys trigger='trigger'></input>
Thanks