Search code examples
angularjsdrop-down-menuangularjs-scope

Store the value of selection from dropdown to a variable AngularJS


I would like to store the value of a selection from a dropdown in AngularJS.

I am able to replicate the new selection on UI but not in console.

<div ng-controller="MyCtrl">
<div>
    Fruit List:
    <select id="fruitsList"
        ng-model="cart"
          ng-change="getSelectedLocation()"

        ng-options="state for state in shelf"></select>
        <br/>
    <tt>Fruit selected: {{cart}}</tt>
</div>

    var myApp = angular.module('myApp', []);

myApp.controller('MyCtrl', function($scope) {

  $scope.cart = "";

  $scope.shelf = ['Banana', 'Apple', 'Pineapple', 'Blueberry'];

  $scope.getSelectedLocation = function() {
    console.log($scope.cart);
  }

  $scope.printSelectedValue = function() {
    if ($scope.cart == 'Banana') {
      console.log("Its a banana")
    } else if ($scope.cart == "Apple") {
      console.log("Its an apple")
    } else {
      console.log("Its neither a banana nor an apple")
    }
  }

});

Any idea on how to achieve that?

jsfiddle link


Solution

  • You're printing the cart once, when the controller is instanciated. At that time, the user hasn't had the chance to select anything yet.

    If you want to print the selection every time it changes, use ng-change (you're already using it, BTW):

    ng-change="printSelection()"
    

    and in the controller:

    $scope.printSelection = function() {
      console.log($scope.cart);
    };