Microsoft introduced great way to copy and paste data using Ctrl + C and Ctrl + V. Lets see how to implement this in AngularJS.

Program Flow 

  1. Bind keydown and keyup status for window and keep track Ctrl button pressing status
  2. Bind keydown for the div which you want find Ctrl + C and Ctrl + V
  3. Use event.preventDefault in detecting Ctrl + S

Script

$scope.ctrlDown = false;
$scope.ctrlKey = 17, $scope.vKey = 86, $scope.cKey = 67;

$scope.keyDownFunc = function($event) {
    if ($scope.ctrlDown && ($event.keyCode == $scope.cKey)) {
        alert('Ctrl + C pressed');
    } else if ($scope.ctrlDown && ($event.keyCode == $scope.vKey)) {
        alert('Ctrl + V pressed');
    } else if ($scope.ctrlDown && String.fromCharCode($event.which).toLowerCase() == 's') {
        $event.preventDefault();
        alert('Ctrl + S pressed');
    }
};

angular.element($window).bind("keyup", function($event) {
    if ($event.keyCode == $scope.ctrlKey)
        $scope.ctrlDown = false;
    $scope.$apply();
});

angular.element($window).bind("keydown", function($event) {
    if ($event.keyCode == $scope.ctrlKey)
        $scope.ctrlDown = true;
    $scope.$apply();
});

6 comments:

  1. I've a question, how can I do it for Ctrl + S event? I changed $scope.sKey = 115 since s is 115 but I couldn't get alert message. Instead, it open browser default save action.

    ReplyDelete
    Replies
    1. Thanks for your comment. Now I have added Ctrl + S functionality also. Find above code

      Delete
  2. Hi Dasari Srinivas
    I'm searching for this. Thank you very much.

    ReplyDelete
  3. @HostListener('window:keydown', ['$event'])
    keyEvent(event: KeyboardEvent) {

    if (event.ctrlKey && event.keyCode == 83)
    {

    }
    }

    this is latest and easy to implement

    ReplyDelete
  4. This is quite a good blog.Are you also searching for BSN Writing Services? we are the best solution for you. We are best known for delivering the best bsn writing services to students without having to break the bank.

    ReplyDelete

Blogroll

Follow this blog by Email

Popular Posts