Issue
I'm watching for keyboard events, specifically left, right, and esc.
Each one is bound to a function that performs some scope function in the page's controller.
These functions do get called when the keys are pressed, however, the scope variables that are supposed to be updated in those functions seem to not do anything.
Is there a scope problem? Is it a problem that I've bound these typing events to the body
?
angular.element( document.body ).bind('keydown keypress', function (event)
{
if(event.which === 27) // 27 = esc key
{
$scope.toggleSize();
// $scope.$apply(function() {
// $scope.fullscreen = !$scope.fullscreen;
// });
console.log('scope', $scope.fullscreen);
event.preventDefault();
} else if(event.which === 37) {
console.log('next');
$scope.goToNextSection('currentSection', $scope.slides);
} else if(event.which === 39) {
console.log('prev');
$scope.goToPreviousSection('currentSection', $scope.slides);
}
});
Solution
Angular only updates things bound to the scope when a digest cycle runs. Most of the time a digest is triggered automatically by Angular in response to some event. When that's not the case, you need to do it yourself. That's precisely what's happening here.
When you listen to DOM events by using jqLite/jQuery you need to tell Angular to trigger a digest after you have changed something in the scope. To do that, just call the $apply() method:
angular.element( document.body ).bind('keydown keypress', function (event)
{
if(event.which === 27) // 27 = esc key
{
$scope.$apply(function() {
$scope.toggleSize();
});
console.log('scope', $scope.fullscreen);
event.preventDefault();
} else if(event.which === 37) {
$scope.$apply(function() {
$scope.goToNextSection('currentSection', $scope.slides);
});
console.log('next');
} else if(event.which === 39) {
$scope.$apply(function() {
$scope.goToPreviousSection('currentSection', $scope.slides);
});
console.log('prev');
}
});
I suggest that you read more about scopes and the digest cycle. Angular documentation itself is a good start.
Finally, I'm not sure whether you're listening to DOM events in your controller. If you are, you probably should use a directive instead.
Answered By - Michael Benford
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.