How to update an angularjs page after an update of the scope?


I have written a directive that captures keyboard events, and on certain keys I update some objects in the scope. The idea is to move up and down an array and display the selected row details. The problem is the page is not updated until I do another action that updates the page. How can I force this?

Here's the directive:

LogApp.directive("keyCapture", [function(){
    var scopeInit;
        link: function(scope, element, attrs, controller){
            scopeInit = scope
            element.on('keydown', function(e){
                scopeInit[attrs.keyCapture].apply(null, [e]);

Bound the template like this:

<body ng-controller="logCtrl" key-capture="movePreview">

The controller method:

$scope.movePreview = function(e){
    if ($ === 0)
    // Find the element
    if (e.keyCode === 38 || e.keyCode === 40){
        console.log("Pressed %s", e.keyCode);
        var offset = 0;
        if (e.keyCode === 38 && $scope.previewIndex > 0)
            offset = -1;
        else if (e.keyCode === 40 && $scope.previewIndex < $ -1 )
            offset = 1;

        $scope.previewIndex += offset;
        var eventId = $[$scope.previewIndex].uuid;

$scope.showEvent(eventId) will take the item with given ID and display it in another part of the page. Part that is not update until another action is performed, like clicking a button. Is it possible to force the page update?

Here's a fiddle that reproduces: If you click on the button, the counter is updated. If you press any key, nothing shows. But you click again on the button, you see the counter has been updated by the keyboard event, but didn't show.

If you are listening to non-angular events:

element.on('keydown', function(e){
    scopeInit[attrs.keyCapture].apply(null, [e]);

Then, to update the scope, you need to call scope.$apply:

element.on('keydown', function(e){
    scopeInit[attrs.keyCapture].apply(null, [e]);

This will kick off an angular $digest cycle and allow changes to bind.