Lovelock
Lovelock

Reputation: 8085

Using angular $scope and ng-model for number adjustment

I am working on a metronome and initially had a div set up with a value of 100:

<div ng-bind="currentBpm"></div>

In my controller I had the scope initially set:

$scope.currentBpm = 100;

I then also have a function that adjusts the tempo:

function adjustBpm(direction) {
    if (direction == false && $scope.currentBpm > 1) {
        $scope.currentBpm = $scope.currentBpm -1;
    } else if (direction == true && $scope.currentBpm < 999) {
        $scope.currentBpm = $scope.currentBpm +1;
    }

    console.log($scope.currentBpm);
}

This worked well, but I need to give the user the option of entering a value using the numeric keyboard.

Switching the div to a number input:

<input type="number" ng-model="currentBpm">

Allows the user to click the input and adjust the value, but the $scope is then not used. The function for adjusting the value still console logs the previous value and not that of the input. Im guessing ng-model moves away from the scope and creates 2 different values.

Is there any way to sync these up?

The adjustBpm function is called on a click of a + / - button.

<div ng-click="adjustBpm(false)"> + </div>

Upvotes: 0

Views: 52

Answers (1)

Damien
Damien

Reputation: 4103

You have to call ng-click and ng-keyup on the input :

<input type="number" ng-model="currentBpm" ng-click="adjustBpm(false)" ng-keyup="adjustBpm(false)">

Or as said @georgeawg you can use ng-change :

<input type="number" ng-model="currentBpm" ng-change="adjustBpm(false)">

Upvotes: 0

Related Questions