How can I detect keydown or keypress event in angular.js?

后端 未结 4 1245
渐次进展
渐次进展 2020-12-23 20:36

I\'m trying to get the value of a mobile number textbox to validate its input value using angular.js. I\'m a newbie in using angular.js and not so sure how to implement thos

4条回答
  •  长情又很酷
    2020-12-23 21:01

    You were on the right track with your "ng-keydown" attribute on the input, but you missed a simple step. Just because you put the ng-keydown attribute there, doesn't mean angular knows what to do with it. That's where "directives" come into play. You used the attribute correctly, but you now need to write a directive that will tell angular what to do when it sees that attribute on an html element.

    The following is an example of how you would do that. We'll rename the directive from ng-keydown to on-keydown (to avoid breaking the "best practice" found here):

    var mod = angular.module('mydirectives');
    mod.directive('onKeydown', function() {
        return {
            restrict: 'A',
            link: function(scope, elem, attrs) {
                 // this next line will convert the string
                 // function name into an actual function
                 var functionToCall = scope.$eval(attrs.ngKeydown);
                 elem.on('keydown', function(e){
                      // on the keydown event, call my function
                      // and pass it the keycode of the key
                      // that was pressed
                      // ex: if ENTER was pressed, e.which == 13
                      functionToCall(e.which);
                 });
            }
        };
    });
    

    The directive simple tells angular that when it sees an HTML attribute called "ng-keydown", it should listen to the element that has that attribute and call whatever function is passed to it. In the html you would have the following:

    
    

    And then in your controller (just like you already had), you would add a function to your controller's scope that is called "onKeydown", like so:

    $scope.onKeydown = function(keycode){
        // do something with the keycode
    }
    

    Hopefully that helps either you or someone else who wants to know

提交回复
热议问题