0

I want to update page for keyboard event. I wired the keyboard event through $window.document.onkeydown. (I know this is not good but it is supposed to work)

However, I find that the page is not updating even the model is changed! Where am I missing ?

<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <script>
          function Main ($scope, $window) {
            $scope.keyCode = 0;
            $window.document.onkeydown = function (event) {
                $scope.keyCode = event.keyCode;
                console.log($scope.keyCode); //the model is changed here
            };
          }
        </script>
    </head>
    <body ng-app>
        <div ng-controller="Main">
          {{keyCode}}
        </div>
        <script type="text/javascript" src="bower_components/angular/angular.js"></script>
    </body>
</html>

---Edit---
Here is the code snippet you can try http://plnkr.co/edit/DFUfHzQPla031IEDdCo3?p=preview

1 Answer 1

3

Whenever you want to execute an expression that is outside Angular's scope you need to let Angular know that a change has been made so it can perform a proper digest cycle. You can do this using the $scope.$apply() method. So your example becomes:

function Main ($scope, $window) {
    $scope.keyCode = 0;
    $window.document.onkeydown = function (event) {
        $scope.$apply(function () {
            $scope.keyCode = event.keyCode;
            console.log($scope.keyCode);
        });
    };
}

Please see updated plunker here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.