Question

I'd like to use ng-keyup to watch for the up and down arrow keys and increment or decrement the value in an input. This seems like it should be straightforward, but this fiddle does not work: http://jsfiddle.net/a8tgW/3/

html

<div  ng-controller="MyCtrl">
  <input type="text" ng-model="minPotatoes" ng-keyup="onKeyup($event, minPotatoes)" />
  <input type="text" ng-model="maxPotatoes" ng-keyup="onKeyup($event, maxPotatoes)" />
</div>

js

function MyCtrl($scope) {
  $scope.onKeyup = function (evt, val) {
    if(evt.keyCode === 40) {
      val -= 1
      console.log("decrementing val", val)
    } else if (evt.keyCode === 38) {
      val += 1
      console.log("incrementing val", val)
    }
  }
  $scope.minPotatoes = 2;
  $scope.maxPotatoes = 10;
}

I've tried using $apply, but a digest is already in progress. I've read this question, but it uses an external listener which doesn't have access to the model reference.

I could reference the scope value directly, instead of the passed in value, but it would be less coupled if the key handler had no knowledge of the model it was impacting.

Was it helpful?

Solution

you want to be changing the scope variable and not the local val variable.

<input type="text" ng-model="potatoCount" ng-keyup="onKeyup($event, 'potatoCount')" />

function MyCtrl($scope) {
    $scope.onKeyup = function (evt, val) {
        if(evt.keyCode === 40) {
            --$scope[val];
            console.log("decrementing val");
        } else if (evt.keyCode === 38) {
            ++$scope[val];
            console.log("incrementing val");
        }
    };
    $scope.potatoCount = 42;
}

http://jsfiddle.net/ALjR5/2

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top