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

4 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

Blogroll

Follow this blog by Email

Popular Posts