0

Fiddle - http://plnkr.co/edit/NizmbUMHblixAUPfQF2G?p=preview

I'm learning AngularJS, and I wanted to try something simple....

Every time I type in a textbox I want to see it's keyCode, (I'm using jQuery in the following function I'm trying to rewrite in this example as jQuery standardizes the keycode event in this case for cross browser consistency)

// Get Keycode/Which
$("[data-action=outputkeycode]").on("keyup", function(e) {
  $(this).val(e.which);
}).on("click", function() {
  $(this).select();
});

Because I'm trying to update the textbox being typed to find the keyCode I figured I'd apply event.keyCode in the value, but it's not working.

<body ng-app="">
  <input ng-keyup="event=$event" value="{{ event.keyCode }}">
</body>

<!doctype html>
<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.min.js"></script>
  </head>
  <body ng-app="">
    <input ng-keyup="event=$event" value="{{ event.keyCode }}">
  </body>
</html>
halfer
  • 19,824
  • 17
  • 99
  • 186
Michael Schwartz
  • 8,153
  • 14
  • 81
  • 144
  • Just a comment in general. I read that your not really supposed to add jQuery to angular, check out this post http://stackoverflow.com/questions/14994391/thinking-in-angularjs-if-i-have-a-jquery-background – Joe Lloyd Aug 15 '15 at 11:43
  • do you want to show the key code in input is that all? – Kalhan.Toress Aug 15 '15 at 11:49

2 Answers2

1

If you need to show the key code in the input then you can use below code

<input ng-keydown="event=$event.keyCode; $event.preventDefault()" ng-model="event">

when key is pressing down which happens before the ng-keyup we will assign the keycode to event scope variable, then we prevent its default action which is type the actual character in textbox.

and assign the ng-model="event" here the text box gets the value of event scope variable

<!doctype html>
<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.min.js"></script>
  </head>
  <body ng-app="">
    <input ng-keydown="event=$event.keyCode; $event.preventDefault()" ng-model="event">
  </body>
</html>

Update

select the text on click in textbox.

You can create a angular directive to select the textbox text, here is a good directive

and here is the updated demo

Community
  • 1
  • 1
Kalhan.Toress
  • 21,683
  • 8
  • 68
  • 92
0

Try this snippet:

<!doctype html>
<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.min.js"></script>
  </head>
  <body ng-app="">
    <input ng-keyup="keyCode=$event.keyCode" ng-model="keyCode">
  </body>
</html>
Praveen Singh
  • 2,499
  • 3
  • 19
  • 29