The AngularJS filter with the jQuery event does not work

advertisements

I have a list of items from $scope, and I bind jQuery event with them, and I use a input field to filter the list. Everything works as expected.

When I type something in the input field, the items filtered out will still be bound with the jQuery event; however, if I delete the text from the input field, the re-appearing items seem to be out of the scope.

You can check this plunker. When I click on the button in the list, an alert will pop up, but if I type b in the input box, and then delete it, clicking the button with text a will not show you the pop up.

How can I fix this?

Thanks in advance.

Update:

Thanks for the answers, I'm sorry to mislead you by using such a simple example :/ the actual situation is quite different. Anyway, using jQuery .on is not a good idea here, what I should do is to pass the $event object to a function within the scope, and handle the DOM element inside that function.


The problem is with the angular filter, you should be clear with its functionality filter just not hide the element from the DOM but also remove that element from the DOM at the very first time events gets attached to the element but when you search through input field no events remain on the same element.

Here is solution

<!DOCTYPE html>
<html>

  <head>
    <link rel="stylesheet" href="style.css">
  </head>

  <body ng-app="test">
    <h1>Hello Plunker!</h1>
    <input type="text" ng-model="ftr">
    <ul ng-controller="TestController">
      <li ng-repeat="item in list | filter : {name : ftr}">
        <button class="item" ng-click='getEvent()'>{{ item.name }}</button>
      </li>
    </ul>
    <script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js"></script>
    <script src="app.js"></script>
  </body>

</html>

.

angular.module('test', [])
.controller('TestController', ['$scope', function($scope) {
  $scope.list = [
    { name: 'a' },
    { name: 'ab' },
    { name: 'abc' },
    { name: 'abcd' },
    { name: 'abcde' }
  ];
  $scope.getEvent = function(){
   $('.item').on('click', function () {alert('ha');});
  }
  setTimeout(function() {
    $('.item').on('click', function () {alert('ha');});
  }, 100);
}]);

One more solution just a tricky .

 $('body').on('click','.item', function () {alert('ha');});

it's method to attach element on future coming element.