使用角度,如何在下拉列表中获取ng-change上的选定值?

时间:2015-01-09 01:28:04

标签: javascript angularjs drop-down-menu angularjs-directive angularjs-ng-change

所以我有一些数据以逗号分隔的字符串。

sizes: "Small,Medium,Large,X Large,XX Large"

我得到一个下拉列表,根据拆分该字符串显示值。

<select ng-options="choice as choice for (idx, choice) in val.sizes.split(',')" 
        ng-change="selected.product.set.size(choice);>

        <option value="">Please select a size</option>
</select>

使用ng-change:如何将选定的值choice传递给函数?

3 个答案:

答案 0 :(得分:9)

您可以使用ng-model并在ng-change回调中访问它,或者直接传递它。

<select ng-model="selectedSize" ng-options="choice as choice for (idx, choice) in val.sizes.split(',')" 
        ng-change="selected.product.set.size(selectedSize)">

        <option value="">Please select a size</option>
</select>

angular.module('app', []).controller('ctrl', function($scope) {
  $scope.sizes = "Small,Medium,Large,X Large,XX Large";
  $scope.handleChange = function() {
    console.log($scope.selectedSize)
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
  <select ng-model="selectedSize" ng-options="choice as choice for (idx, choice) in sizes.split(',')" ng-change="handleChange()">

    <option value="">Please select a size</option>
  </select>
</div>

答案 1 :(得分:0)

对我来说只使用一个简单的变量使用ng-model不起作用!所以$ scope.selectedSize将为我返回undefined和$ scope.selectedSize =&#34;大小和#34;不会改变选择下拉模型。

这是否可以这样工作(byValue / byRef变量)?

使用ng.model =&#34; whatever.selectedSize&#34;和$ scope.whatever.selectedSize一样,用于获取和设置下拉列表/模型的值。

答案 2 :(得分:-1)

这肯定有帮助。

<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.js"></script>

<div ng-controller="manageroles_controller" ng-app="app_manageroles">

    <select title="Update Role Hierarchy" name="cmb_role_hierarchy" id="cmb_role_hierarchy" ng-model="cmb_role_hierarchy" ng-change="updateRoleHierarchy('cmb_role_hierarchy');">

        <option ng-init="cmb_role_hierarchy=5" value="5">5</option>

    </select>

</div>

var app_manageroles =  angular.module('app_manageroles',[]);
app_manageroles.controller('manageroles_controller', function($scope,$http) {   
    $scope.updateRoleHierarchy = function(cntRoleHierarchy) {
        alert(cntRoleHierarchy);
    }
});