Güney Güney - 7 months ago 18
Javascript Question

Cannot set a scope inside document.bind

I'm trying to reset two scopes that defined before on an "esc" keyup event but it apparently does not work when I check out them. $document is defined on my controller's dependencies.

Here is what I've tried:

$document.bind('keyup', function (event) {
if (event.keyCode == 27) {
$scope.currentPage = false;
}
});


I also tried the jQuery way. It doesn't work as well:

jQuery(document).keyup(function (event) {
if (event.keyCode == 27) {
$scope.currentPage = false;
}
});


What am I missing? What's wrong? Thanks in advance!

Answer

Use $scope.$apply(function() { ... }); to force the Angular digest cycle to run.

Your code will be:

$document.bind('keyup', function (event) {
  if (event.keyCode == 27) {
    $scope.$apply(function() {
        $scope.currentPage = false;
    });
  }
});
Comments