Search code examples
javascriptangularjsejsangular-directive

$scope variable not updating in view after broadcast event from directive


I have read similar questions and I can't put my finger on why this is not updating. I can get logs of the scope variable updating on the catch events. But it's not updating the view. So it populates with "test", but will not update when $scope.keyPressed is being updated.

the directive

app.directive('keypressEvents', [
  '$document',
  '$rootScope',
  function($document, $rootScope) {
    return {
      restrict: 'A',
      link: function() {
        $document.bind('keypress', function(e) {
          console.log('Got keypress:', e.which);
          // console.log('document', $document)
          $rootScope.$broadcast('keypress', e);
          $rootScope.$broadcast('keypress:' + e.which, e);
        });
      }
    };
  }
]);

the controller

$scope.keyPressed = 'test';
$scope.$on('keypress:13', function(onEvent, keypressEvent) {
          $scope.keyPressed = 'Enter';
          console.log($scope.keyPressed);
        });
        // For listening to all keypress events
        $scope.$on('keypress', function(onEvent, keypressEvent) {
          if (keypressEvent.which === 120) {
            $scope.keyPressed = 'x';
          }
          else {
            console.log('else' ,keypressEvent);
            $scope.keyPressed = 'Keycode: ' + keypressEvent.which;
          }
        });

the view

<div data-keypress-events>
    {{keyPressed}}
</div>

The controller for the view is dictated by the route provider when it loads the partial.

.when('/feed/:url', {
            templateUrl: '/templates/eventWall-feed',
            controller: 'eventWallFeedController'
        })

Solution

  • $on and $broadcast do not call $apply therefore you need to wrap $scope.keypPressed in an $apply like

    $scope.$apply(function() {
      $scope.keyPressed = 'x';
    });