0

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

0

1 Answer 1

1

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);
};
Sign up to request clarification or add additional context in comments.

8 Comments

Yeah. But how do I store that to a variable? If I select bananas, I want that to be stored to a variable and if I select apple, the new value for that variable should be "apple"
So I return $scope.cart inside the printSelection function and how do I use the selected values inside other functions? jsfiddle.net/Td2NZ/2172 Why doesnt the console print anything now?
Because you're, once again, printing abcd once, when the controller is instanciated. At that time, the user hasn't had the chance to select anything yet. Move the console.log() statement inside the getSelectedLocation function.
Yeah okay. Is there a way to return that to a variable and can use that value in any part of the controller?
You can use $scope.cart, wthout that useless abcd variable, from anywhere in the controller. You just need to understand when instructions are executed. Instructions that are directly in the controller function are executed once, when the controller is instanciated.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.