简体   繁体   中英

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);
    };
});

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);
    };
});

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM