-2

Starting with the following html code

<div ng-repeat="item in list">
    <input type="text" class="texter">
</div>

I use jquery to listen on keypress on any input listed.

$('.texter').keypress(function(e){
    console.log(this);
}

but nothing happens. Even with

$('input').keypress(function(e){
    console.log(this);
}

Basically, I want to get the element where keypress event is fired.

Is there a way to get it with jquery?

Note that I already searched for an answer before asking but none seems to do what I'm expecting.

Buu97
  • 158
  • 2
  • 15
  • 1
    This is why it's not a good idea to mix jQuery and Angular -- every time Angular redraws the DOM it's going to blow away the jQuery event bindings that it doesn't know about. Handle the keypress event within Angular instead. – Daniel Beck Jul 30 '18 at 15:01
  • try wrapping it with `$timeout`. It can't grab your classes because they are not rendered yet. jQuery is not part of that digest cycle for rendering. DOM modifications are for directives, which use JQLite that you could try to use – Aleksey Solovey Jul 30 '18 at 15:01
  • I recommend strongly Angular solution, but $(document).on('keypress', '.texter', function(){console.log($(this))}) would work – Roy Bogado Jul 30 '18 at 15:03
  • so how do I handle the keypress event with angular? – Buu97 Jul 30 '18 at 15:09

1 Answers1

1

Why are you using jQuery to bind event listeners? You can do this properly with Angular by adding ng-keypress to your input inside your ng-repeat

Angular

HTML

<div ng-repeat="item in list">
  <input type="text" class="texter" ng-keypress="keypress($event)">
</div>

JS

angular
  .module("myApp", [])
  .controller('myController', ['$scope', function($scope) {

    $scope.list = [1,2,3];

    $scope.keypress = function(event){
      console.log(event);
    }
  }]);

DEMO

You should use $(document).on('keypress', ...) if you insist on handling the event bindings using jQuery

$(document).on('keypress', '.texter', function(e){
  console.log(e);
});
dysfunc
  • 2,008
  • 1
  • 13
  • 15
  • The use of `delegate` has be deprecated for awhile.... – epascarello Jul 30 '18 at 15:19
  • Updated the answer to use `on` – dysfunc Jul 30 '18 at 15:20
  • I don't think this should be flagged as a duplicate post. It's a partial answer to the linked post given it's related to Angular, and jQuery shouldn't be used for bindings. Maybe change the title to something with more context and relevance "How to bind the keypress event to an input inside an ng-repeat" – dysfunc Jul 30 '18 at 15:25