제이쿼리에서는 쉽게 키프레스를 할 수 있지만 앵귤러js에서는 약간 복잡하다.

 

Angularjs로 키 값을 감지하는 방법은 ng-keypress 또는 directive로 ng-enter 같은 것을 만드는 것이 있다.

 

1. ng-keypress 이용

<!doctype html>
<html>

<head>
    <title>앵귤러 연습</title>

    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular-route.js"></script>
    <script src='https://code.jquery.com/jquery-3.3.1.min.js'></script>

</head>

<body>

    <div ng-app="myApp" ng-controller="myCtrl">
        <input type="password" ng-model="userpw" ng-keypress="onKeyPress($event)">
        <h5>{{onKeyPressResult}}</h5>
        <h5>눌른 키 코드: {{pressedKey}}</h5>
    </div>

    <script>
        //angulare 영역

        var app = angular.module("myApp", []);

        app.controller('myCtrl', function($scope, $http, $rootScope, $location) {
            
            $scope.onKeyPressResult = "";
            
            //눌린 키값을 가져온다.
            var getKeyboardEventResult = function (keyEvent){
                return(window.event ? keyEvent.keyCode : keyEvent.which);
            }
            
            //키 클릭 메소드
            $scope.onKeyPress = function($event){
                console.log("키눌림");
                $scope.pressedKey = getKeyboardEventResult($event);
                
                
                if(getKeyboardEventResult($event) == 13){
                    $scope.onKeyPressResult = "Enter key pressed";
                    
                }else{
                    $scope.onKeyPressResult = "not pressed enter key";
                }
                
            }
    
        });
   
    </script>

</body>

</html>

위와 같은 html 파일을 생성하고 인풋에 엔터가 아닌 자판을 입력하면 이렇게 나오고

엔터가 아닌 키를 입력시

 

엔터를 누르면 아래와 같이나온다.

엔터는 가운데 엔터키나 오른쪽 엔터키나 같이 13코드로 적용된다.

 

 

 

 

 

+ Recent posts