1

Based on below controller, I think the <div> with ngShow should appear when the left keyboard arrow is pressed.

The $scope does update (which can be seen as its printed to console) but the DOM doesn't change.

But when i type something into the input field, the <div> then appears. So its like angular is not watching for changes I'm making with keydown.

Controller

.controller('TestCtrl', ['$scope', '$document', function($scope, $document) {
    var keyboardMap = { 37: 'left'};
    $document.on('keydown', function (event) {
        var key = keyboardMap[event.which];
        if (key) {
            console.log('lefty');
            $scope.left = true;
        } 
    });
}]);

View

<div ng-app="TestApp" ng-controller="TestCtrl">
    <div ng-show="left" style="height: 100px; width: 100px; border: 1px black solid;"></div>
    <input ng-model="something"></input>
</div>

I read a few other similar question on SO but didn't find them helpful. I do feel like theres something I don't understand here though.

Does anyone know why its not updating, and how I could make it update?

tim_xyz
  • 11,573
  • 17
  • 52
  • 97

2 Answers2

4

Please execute $digest() as AngularJS doesn't know anything about on event.

function TestCtrl($scope, $document) {
  $document.on('keydown', function(event) {
    var keyboardMap = {
      37: 'left'
    };
    var key = keyboardMap[event.which];
    if (key) {
      $scope.left = true;
      $scope.$digest()
    }
  });
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app ng-controller="TestCtrl">
  <div ng-show="left" style="height: 100px; width: 100px; border: 1px black solid;"></div>
  <input ng-model="something">
</div>
Krzysztof Safjanowski
  • 7,292
  • 3
  • 35
  • 47
2

Wrap your code in a $apply block:

if (key) {
            console.log('lefty');
            $scope.$apply(function() {
                $scope.left = true;
            });
        } 

This forces model updates from events from the outside of angulars world. Documentation

Edit: $scope.$digest() is another way to do this. Read here for an explanation of the differences.

Community
  • 1
  • 1
Fidel90
  • 1,828
  • 6
  • 27
  • 63