Krishna Kumar
Krishna Kumar

Reputation: 2121

AngularJS: ng-keypress is not working

Problem: ng-keypress is not working but if I replace ng-keypress with ng-click then filterSearchData($event) function is working.

HTML:-

<!DOCTYPE html>
<html ng-app="myApp">
    <head lang="en">
        <meta charset="utf-8">
        <title>Custom Plunker</title>  
        <link rel="stylesheet" type="text/css" href="ng-grid.css" />
        <link rel="stylesheet" type="text/css" href="style.css" />
        <script src="jquery.min.js"></script>
        <script src="angular.min.js"></script>
        <script type="text/javascript" src="ng-grid.debug.js"></script>
        <script type="text/javascript" src="main.js"></script>
    </head>
    <body>
        <body ng-controller="MyCtrl">
            <input type="text" ng-keypress="filterSearchData($event)" />
            <div class="gridStyle" ng-grid="gridOptions"></div>
        </body>
    </body>
</html>

JS:-

var app = angular.module('myApp', ['ngGrid']);
app.controller('MyCtrl', function($scope, $http) {
    $scope.filterSearchData = function(element) {
        console.log(element);
    };
});

Upvotes: 1

Views: 6093

Answers (2)

dfsq
dfsq

Reputation: 193261

If for some reason you have to use such an old version of angular, which doesn't support ngKeypress directive, you can always add your own implementation. It's pretty easy to do, for example onKeypress directive:

app.directive('onKeypress', function() {
    return {
        scope: {
            handler: '&onKeypress'
        },
        link: function(scope, element) {
            element.bind('keypress', function(e) {
                scope.handler({$event: e});
            });
        }
    };
});

HTML:

<input type="text" on-keypress="filterSearchData($event)" />

Demo: http://plnkr.co/edit/OorXMYKZeXI9Lrc1wrRY?p=preview

Upvotes: 2

Dennis Traub
Dennis Traub

Reputation: 51624

In this case I recommend to use ng-change instead of ng-keypress.

// HTML:
<input type="text" ng-model="filter" ng-change="filterSearchData()" />

// Controller:
app.controller('MyCtrl', function($scope, $http) {
    $scope.filterSearchData = function() {
        console.log($scope.filter);
    };
});

Upvotes: 2

Related Questions