将下拉列表中的选择值存储到变量 AngularJS

Store the value of selection from dropdown to a variable AngularJS

我想将从下拉列表中选择的值存储在 AngularJS。

我可以在 UI 上复制新选择,但不能在控制台中复制。

<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")
    }
  }

});

知道如何实现吗?

jsfiddle link

当控制器实例化时,您将打印一次购物车。那时,用户还没有机会 select 任何东西。

如果您想在每次更改时打印 selection,请使用 ng-change(顺便说一句,您已经在使用它了):

ng-change="printSelection()"

在控制器中:

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