Home > Enterprise >  Changing the value of a dropdown when the value of a number box changes in AngularJS
Changing the value of a dropdown when the value of a number box changes in AngularJS

Time:04-02

Let us say that I have two inputs: a number field and a dropdown:

<input name="nameForNumberField" ng-model="pizzaBox.numSlices" type="number" ng-change="onNumSlicesChanged()"/>

<select id="nameForDropdown" data-ng-model="pizzaBox.selectedPizzaSize" ng-options="x for x in pizzaBox.pizzaSizes"></select>

I would consider a pizza box with 8 or less slices as small and a pizza box with more than 8 slices as large. By default, the pizza box has 5 slices, and therefore is small.

$scope.pizzaBox = { 
numSlices: 5, 
pizzaSizes: ["Small", "Large"], 
selectedPizzaSize: "Small" 
};

$scope.onNumSlicesChanged = function () {
    if ($scope.pizzaBox.numSlices <= 8) {
        $scope.selectedPizzaSize = "Small";
    }
    else {
        $scope.selectedPizzaSize = "Large";
    }
};

What I want is that when I change the number field to a number greater than 8, I expect the value of the dropdown to switch from Small to Large. In a similar matter, if the number in the number box is greater than 8 and the dropdown value is at large, when I change the number value to 4, I expect that the dropdown value changes from Large to Small.

I tried the code outlined above. What happened is that as I was changing the number in the number field, the value selected in the dropdown did not change at all. The only way I was able to change the value of the dropdown was to click into the dropdown and manually change it. I would only want to do that AFTER the front-end has already defaulted to its chosen pizza size via the logic outlined above.

I am expecting that as I change the value in the number field, the value in the dropdown will automatically change per the logic described.

CodePudding user response:

You want to reference $scope.pizzaBox.selectedPizzaSize, not $scope.selectedPizzaSize

angular.module('myApp', [])
  .controller('myCtrl', ['$scope', '$http', function($scope, $http) {
    $scope.pizzaBox = {
      numSlices: 5,
      pizzaSizes: ["Small", "Large"],
      selectedPizzaSize: "Small"
    };

    $scope.onNumSlicesChanged = function() {
      if ($scope.pizzaBox.numSlices <= 8) {
        $scope.pizzaBox.selectedPizzaSize = "Small";
      } else {
        $scope.pizzaBox.selectedPizzaSize = "Large";
      }
    };
  }]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
  <input name="nameForNumberField" ng-model="pizzaBox.numSlices" type="number" ng-change="onNumSlicesChanged()" />
  <select id="nameForDropdown" data-ng-model="pizzaBox.selectedPizzaSize" ng-options="x for x in pizzaBox.pizzaSizes"></select>
</div>

  • Related