Reputation: 1686
As you know using Boostrap drop-down components you are not able to select an element by pressing the Keyboard Letter. So i was using the following code which use a directive
myApp.directive('keyLetterPressed', function ($timeout) {
return function (scope, element, attrs) {
element.bind("keydown keypress", function (event) {
var target = $(event.target);
$(target).trigger('focus');
});
};
});
but this is not complete, actually is not working, just you can tell me
how do i go to the element which have the same letter of the list ?
Also i have to put this directive in the Ul element ?
Because actually I am using it on the li
<li ng-repeat="v in values" keyLetterPressed>{{v.name}}</li>
Upvotes: 0
Views: 2928
Reputation: 1686
This can be an a partial answer as you can see it worked just need a little adjustments.
Check this jsfiddle
Here is the code :
myApp.directive('keypressEvents',
function ($document, $rootScope) {
return {
restrict: 'A',
link: function (scope, element, attr) {
console.log('linked');
$document.bind('keypress', function (e) {
$rootScope.$broadcast('keypress', e, String.fromCharCode(e.which));
var letter = String.fromCharCode(e.which);
var target = e.target;
var charat = element[0].textContent.charAt(0);
if(charat === letter){
element.addClass("red");
}
});
}
}
});
Up there is the directive used, it simply is bound on the keypressed and in the end set the class for the element found with the same first letter just I need to set the focus on this and not just change the class
<div class="dropup">
<button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu2" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Dropup
<span class="caret"></span>
</button>
<ul class="dropdown-menu" aria-labelledby="dropdownMenu2">
<li keypress-events><a href="#">action</a></li>
<li keypress-events><a href="#">something else here</a></li>
</ul>
</div>
I have bound the directive on the li
elements.
(rootscope and brodcast message was needed just for debugging)
Upvotes: 0
Reputation: 1686
another answer is this, adding the directive to the ul element
app.directive('booststrapDropdown',
function () {
return {
restrict: 'A',
link: function (scope, element, attr) {
console.log('linked');
element.parent().bind('keypress', function (e) {
children = element.children();
children.removeClass("active");
for (var i = 0; i < children.length; i++) {
var letter = String.fromCharCode(e.which);
var charat = children[i].textContent.replace(/\s+/, '').charAt(0);
if (charat === letter) {
children[i].className += " active";
element[0].scrollTop = children[i].offsetTop;
}
}
});
}
};
});
<div class="btn-group" dropdown>
<button type="button" class="btn btn-primary dropdown-toggle"
dropdown-toggle>
Button dropdown <span class="caret"></span>
</button>
<ul booststrap-dropdown class="dropdown-menu scrollable-menu" role="menu" >
<li ng-repeat="v in values">
<a href="#">{{v.name}}</a>
</li>
</ul>
</div>
Upvotes: 1