使用嵌套的 ng-option 时,如何从下拉列表中将选定的值放入范围?

How to get selected values into scope from drop down while using nested ng-option?

以下是我用来填充多个 select 下拉菜单的视图代码

<div ng-controller="sourceController">
  <form novalidate ng-submit="submit()">
    <div class="row">
      <div class="addNewButton">
        <button type="button" class="btn btn-info btn-sm" data-toggle="modal" data-target="#myModal">Add New Data Source</button>
        <div ng-include="'pages/modal.html'"></div>
      </div>
    </div>
    <div class="row">
      <div class="col-sm-3">
        Location:
        <select id="location" ng-model="location" ng-options="city for (city, facilities) in sourceSelection " style="width: 100px">
          <option value=''>Select</option>
        </select>

      </div>

      <div class="col-sm-3">
        Facility:
        <select id="facility" ng-disabled="!location" ng-model="facility" ng-options="facility for (facility, phases) in location">
          <option value=''>Select</option>
        </select>

      </div>

      <div class="col-sm-3">
        Phase :
        <select id="phase" ng-disabled="!facility" ng-model="phase" ng-options="phase for phase in facility">
          <option value=''>Select</option>
        </select>

      </div>

      <div class="col-sm-3">
        Device Type
        <select id="deviceType" ng-disabled="!phase" ng-model="deviceType">
          <option value=''>Select</option>
          <option ng-repeat="deviceType in deviceTypes" value="{{deviceType}}">{{deviceType}}</option>
        </select>
      </div>
    </div>

    <input type="submit" id="submit" value="Submit" />

  </form>
  <button onclick="myFunction()">click here</button>
  selected choices : {{location}} , {{facility}},

</div>

我使用的控制器是

app.controller('sourceController', function($scope, $http, $rootScope) {
  $scope.sourceSelection = {
    "Chennai": {
      "siruseri": ["phase1", "phase2"],
      "chennai one": ["phase1"]
    },
    "kochi": {
      "Kochi_technopark": ["phase1"]
    }
  };
});

现在我想绑定 selected 字段(即 selected location , Facility , phase in controller)和控制器端的 $scope 以及我在那里使用的模型给我 selected 下拉键的值。

您可以在控制器中检索 selected 值,因为您在 select.

中使用 ng-model="FIELD"

因此,如果您想在控制器中获取值,您可以使用:

$scope.FIELD // FIELD can be location, phase, facility, etc

此变量将存储每个 select 的 selected 选项的值。

您可以添加 ng-change 事件来获取选定的位置,

<select id="location" ng-change="getSelectedLocation()" ng-model="location" ng-options="city for (city, facilities) in sourceSelection " style="width: 100px"><option value=''>Select</option></select>

在您的控制器中,

app.controller('sourceController', function($scope, $http, $rootScope) {

     $scope.getSelectedLocation = function() {

        console.log($scope.location);
     }
});

下面两行是我从同事那里得到的答案

$scope.getSelectedLocation= function(){
        var temp = document.getElementById("location");
        var location = temp.options[temp.selectedIndex].value;
      console.log(location);
} ;