How to keypress in AngularJS - javascript

I have the following code:
index.html:
<a href="" class=”buttonone" ng-click="tool.disc()">
<i class=”buttonone"></i>
</a>
controller.js:
angular.module(’app')
How can I make so that when someone presses a keystroke example 'enter key' the tool.disc() method gets triggered? I suppose I can use angularjs ngKeydown directive but I dont know how to implement it in the code example above. Could someone try to help? Thanks!

You cannot directly call the function specifically on Enter key press, use a function to check if the Enter key is pressed and then call your function.
You cannot listen Keypress event on anchor.
HTML:
<input type="text" ng-keypress="myFunc(e)" />
<!-- ^^^^^^^^^^^^^^^^^^^^^^^ -->
<i class=”buttonone"></i>
Controller:
$scope.myFunc = function (event) {
if (event.keyCode === 13) {
console.log('Enter key pressed');
$scope.tool.disc(); // Call your function here
}
};

The element needs to be in focus to work. To make this example work you will need to click the link and then press a key.
Keydown
$scope.keydown = function (event) {
if (event.keyCode === 13) {
console.log('Enter key pressed');
}
};
To auto focus on the element once loaded you could use
element[0].focus()
Otherwise, consider the follow:
$document.addEventListener('keyup', function (e) { console.log(e) })

ng-keypress or ng-keydown can do the trick :
<div ng-keypress="yourFunction($event)> </div>
And then in your function, you can test the code of the key with
$event.keyCode;
For example, if you want to chech on enter :
$scope.yourFunction = function(event){
if(event.keyCode == 13){
console.log("Enter press");
}
}
Edit :
Because sometime it doesn't work as much as angular wanted it, there is a directive :
app.directive('ngEnter', function () {
return function (scope, element, attrs) {
element.bind("keydown keypress", function (event) {
if(event.which === 13) {
scope.$apply(function (){
scope.$eval(attrs.ngEnter);
});
event.preventDefault();
}
});
};
});
Here this one is for enter, you can change the keycode if you need. To use it you can simply do this in every element :
<a href="" class="buttonone" ng-enter="function()" ng-click="tool.disc()">
<i class=”buttonone"></i>
</a>

Related

JavaScript focusout and specific key

I have the following:
$(selectorClass).focusout(function (e) {
which is triggering if the focus is changed, but how can I modify this so that it also triggers if the enter key is pressed?
Anyone have any examples?
You can factorise your code calling the same function in both events :
function MyCallBack(e)
{
// Your event code goes there
console.log("called");
}
$("#test").focusout(MyCallBack);
$("#test").on('keypress', function(e)
{
if(e.which == 13) // check enter/return key
MyCallBack(e);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="test">
Since you have already written code for focusout event, all you need to just trigger the event when enter key is pressed.
jQuery trigger can be used.
$(document).keyup(function(e) {
if (e.key === "13") { // check enter/return key
$(selectorClass).trigger("focusout");
}
});

ngblur and enter event : why on enter key two http calls go?

I have a form in which I have enter-key press event and ng-blur. It's like when a user enters something and click elsewhere the form is submitted similarly if a user writes something and press enter the form is submitted and API call goes.
Problem Statement
It works fine on ng-blur only a single call goes to the API. But when I try to use key event two calls go. That's why two success messages show. I don't know why but it acting like that.
Form
input ng-model="cusBoard.boardData.musicalWorkName"
id="superTitleInput" class="title-edit-input superTitle-input" type="text"
maxlength="50"
my-key-enter="cusBoard.updateInfo()"
ng-blur="cusBoard.updateInfo()">
My-key-enter Directive
app.directive('myKeyEnter', function () {
return {
controller: 'SignInController',
link: function (scope, elements, attrs) {
elements.bind('keydown keypress', function (event) {
if (event.which === 13) {
scope.$apply(function () {
scope.$eval(attrs.myKeyEnter);
});
event.preventDefault();
}
});
}
}
controller function
function updateInfo(){
editable('superTitle',0);
var params = {
superTitle : cusBoard.boardData.musicalWorkName,
boardId : cusBoard.boardData._id
};
CastingBoard.updateSuperTitle(params).then(function (res) {
if (res.msgCode === '405') {
$mdToast.show($mdToast.simple().textContent("Board title updated successfully.").position('bottom right'));
}
});
}
You're binding to both the keydown and keypress events:
elements.bind('keydown keypress', function (event) {
Both events are fired for the Enter key, so the handler is executed twice.
Just pick one, or the other.

piece of jquery code is not working in angular directive

i have a directive that has several inputs inside of it, and i have an specific input that i need to execute a function when enter is pressed.
This is the input that i need to execute a function.
<input type="text" class="form-control" ng-model="cep" id="inputcep">
And i have a jquery function that uses a mask plugin and a keypress listener that prevents the default action of the enter key and executes the function. My problem is that the keypress is not being called, but the mask is being applied :/
$(document).ready(function () {
$('#inputcep')
.keypress(function(ev){
console.log(ev);
if(ev.keyCode == 13){
ev.preventDefault();
scope.searchCep(scope.cep);
}
})
.mask('00000-000');
});
Use angular instead of jQuery :
https://docs.angularjs.org/api/ng/directive/ngKeypress
Do create you custom directive as below.
Directive
app.directive('customDir', function() {
return function(scope, element, attrs) {
element.bind("keydown keypress", function(event) {
element.keypress(function(ev) {
console.log(ev);
if (ev.keyCode == 13) {
ev.preventDefault();
scope.searchCep(scope.cep);
}
}).mask('00000-000');
});
};
});

Angular keydown directive

I haven't found a solution for this problem. I need to by pressing the spacebar do some actions with the selected item. All solutions were made ​​using input. Any idea how to improve this code? For example don't use jQuery?
Directive:
app.directive('space', function () {
return function (scope, elm, attrs) {
$('body').keydown(function (e) {
if (e.keyCode == 32) {
console.log(e);
// Actions with data
}
})
}
});
Html:
<div class="col-md-12" ng-controller="ReceiptCtrl" space>
// My page
</div>
Ok. I need highlight element by clicking and then in any part of my page by keydown spacebar do something with highlighted element. ng-keydown, ng-keypress and etc. not want to work. Code that i wrote above work fine but it's look awful, I think.
elm.onkeydown = function(e)
{
if(e.keyCode == 32)
// Do some actions
};

jQuery event binding with accessibility in mind - click and keypress

Just a quick question, I seem to do this a lot:
$saveBtn.bind("click keypress", function(e)
{
if (e.type != "keypress" || e.keyCode == 13)
{
// Do something...
return false;
}
});
Is there a quicker way to bind an 'action' listener to a button? I want to always ensure my buttons with event listeners fire on both clicks and the enter key...this seems like it'd be a fairly common thing to want to do but found nothing on google. Any thoughts?
Thanks.
The click event doesn't actually handle the keypress in every case, it's the button that is making the click event work. When you use a div with a tabindex attribute to make it keyboard accessible, the click handler will not trigger when you press enter.
HTML
<div id="click-only" tabindex="0">Submit click only</div>
<div id="click-and-press" tabindex="0">Submit click and press</div>​
jQuery
$("#click-only").click(function (e) {
addToBody(); // Only works on click
});
$("#click-and-press").bind("click keypress", handleClickAndPress(function (e) {
addToBody(); // Works on click and keypress
}));
function addToBody() {
$("body").append($("<p/>").text("Submitted"));
}
function handleClickAndPress(myfunc) {
return function (e) {
if (e.type != "keypress" || e.keyCode == 13) {
myfunc(e);
}
};
}
So to answer the question, I don't think there is a better way (that works in every case) other than yoda2k's solution.
By binding it with click will do the job, no need for keep press. Example
You could create a second function which handles the additional logic and pass your function as a parameter:
function handleClickAndPress(myfunc)
{
return function (e) {
if (e.type != "keypress" || e.keyCode == 13) {
myfunc(e);
}
};
}
$saveBtn.bind("click keypress", handleClickAndPress(function (e) {
// do your stuff here
}));
If it's part of a form you could just listen for the "submit" event?

Categories

Resources