我是AngularJS的新手并尝试从Dropdown获取Selected Text和Value.我跟着很多教程仍然无法到达那里. SelectedValue和SelectedText始终未定义.以下是我的代码:
HTML:
<div ng-app="SelectApp"> <div ng-controller="selectController"> <select name="category-group" id="categoryGroup" class="form-control" ng-model="itemSelected" ng-change="onCategoryChange(itemSelected)"> <option value="0">Select a category...</option> <option ng-repeat="category in categories" value="{{category.id}}" ng-disabled="category.disabled" ng-class="{'mainCategory' : category.disabled}"> {{category.name}} </option> </select> </div>
JS:
'use strict'; var app = angular.module('SelectApp',[ ]); app.controller('selectController',['$scope','$window',function ($scope,$window) { $scope.categories = [ { id: 1,name: "- Vehicles -",disabled: true },{ id: 2,name: "Cars" },{ id: 3,name: "Commercial vehicles",disabled: false },{ id: 4,name: "Motorcycles",{ id: 5,name: "Car & Motorcycle Equipment",{ id: 6,name: "Boats",{ id: 7,name: "Other Vehicles",{ id: 8,name: "- House and Children -",{ id: 9,name: "Appliances",{ id: 10,name: "Inside",{ id: 11,name: "Games and Clothing",{ id: 12,name: "Garden",disabled: false } ]; $scope.onCategoryChange = function () { $window.alert("Selected Value: " + $scope.itemSelected.id + "\nSelected Text: " + $scope.itemSelected.name); }; }]);
还有一件事,我已将我的第一项定义为选择类别…然后为什么Dropdown中的第一项始终为空.
下面是我的小提琴样本.
http://jsfiddle.net/Qgmz7/136/
解决方法
那是因为,你的模型itemSelected捕获你的选择下拉列表的当前值,这只是你的选项元素的value属性.你有
<option ng-repeat="category in categories" value="{{category.id}}">
在你的代码中,所以在渲染版本中,你会得到
<option ng-repeat="category in categories" value="0">
但是你期望itemSelected成为你的类别对象,任何查询id或其他属性的尝试都将返回undefined.
您可以将ng-options与group by一起使用,只需对数据进行一些更改,或者您可以使用常规ng-repeat,获取selectedIndex并使用该索引从类别列表中查找类别对象.在这里展示第一种方法.
HTML
<select name="category-group" id="categoryGroup" ng-model="itemSelected" ng-change="onCategoryChange(itemSelected)" ng-options="category.name group by category.group for category in categories"> </select>
更新数据
$scope.categories = [ { id: 0,name: "Select a category..."},{ id: 1,name: "Cars",group : "- Vehicles -" },group : "- Vehicles -" } ]; $scope.itemSelected = $scope.categories[0];
您可以添加可在group by中使用的组属性,而不是已禁用的属性.
这里有一个更新的Fiddle来说明这个想法.