AngularJS:ng-keypress不起作用

时间:2014-09-29 19:25:39

标签: javascript jquery angularjs angular-ui

问题:ng-keypress无效,但如果我将ng-keypress替换为ng-click,则filterSearchData($event)功能正在运行。

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

2 个答案:

答案 0 :(得分:2)

在这种情况下,我建议使用ng-change代替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);
    };
});

答案 1 :(得分:2)

如果由于某种原因你必须使用这种不支持ngKeypress指令的旧版角度,你可以随时添加自己的实现。这很容易做到,例如onKeypress指令:

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)" />

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