Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I update an angularjs page after a scope update?

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;
    return{
        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 ($scope.events.length === 0)
        return;
    // 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 < $scope.events.length -1 )
            offset = 1;

        $scope.previewIndex += offset;
        var eventId = $scope.events[$scope.previewIndex].uuid;
        $scope.showEvent(eventId);
        e.preventDefault();
    }
};

$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: http://jsfiddle.net/gM2KF/1/ 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.

like image 888
Antoine Avatar asked Jan 30 '26 08:01

Antoine


1 Answers

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]); 
    scope.$apply();               
});

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

like image 76
Davin Tryon Avatar answered Feb 01 '26 23:02

Davin Tryon