skip to Main Content

I have a select dropdown I’m setting up with an ng-options. It’s showing up fine in the HTML page, but when I select an option, the variable defined by ng-model is not being updated in $scope.

HTML:

<select ng-model="selected_ingredient"
        ng-options="item as item.ingredient for item in available_ingredients"
        ng-change="selectIngredient()">
    <option value="">Add an ingredient...</option>
</select>

AngularJS:

$scope.selectIngredient = function() {
    if ( $scope.debug > 0 ) {
        console.log( "Selected ingredient:" );
        console.log( $scope.selected_ingredient );
    }
};

Console output (after dropdown item selected, $scope.debug is 1):

Selected ingredient:
undefined

I would like $scope.selected_ingredient to be the object item that is displayed by the dropdown element I select. What am I doing wrong?

2

Answers


  1. Chosen as BEST ANSWER

    I used a workaround from @billy_comic in the comments

    <select ng-model="$parent.selected_ingredient"
            ng-options="item as item.name for item in available_ingredients"
            ng-change="$emit( 'SelectedIngredient', $parent.selected_ingredient )">
        <option value="">Add an ingredient...</option>
    </select>
    

    in my HTML as well as the following JS function

    $scope.$on( "SelectedIngredient" , function( evt, data ) {
        if ( $scope.debug > 0 ) {
            console.log( "Selected ingredient:" );
            console.log( data );
        }
    });
    

    that produces the expected values. Thanks so much!


  2. Your code appears to work for me. Maybe you’ve made a mistake in the initialization or in some part of the code you haven’t shown.

    angular.module("exampleApp", [])
      .controller("selectIngredientCtrl", function ($log, $scope) {
        $scope.availableIngredients = [
          {ingredient: "foo"},
          {ingredient: "bar"},
          {ingredient: "baz"},
        ];
        $scope.selectedIngredient = null;
        $scope.selectIngredient = () => {
          $log.log($scope.selectedIngredient?.ingredient);
        };
      });
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.js"></script>
    <div ng-app="exampleApp" ng-controller="selectIngredientCtrl">
      <select
        ng-model="selectedIngredient"
        ng-options="item as item.ingredient for item in availableIngredients"
        ng-change="selectIngredient()"
      >
        <option value="">
          Add an ingredient...
        </option>
      </select>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search