Javascript Angularjs 下拉 OnChange 选定的文本和值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31885059/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:19:48  来源:igfitidea点击:

Angularjs Dropdown OnChange Selected Text and Value

javascriptjqueryhtmlangularjsangularjs-ng-options

提问by Usman Khalid

I am new to AngularJSand trying to get Selected Text and Value from Dropdown. I followed a lot of tutorials with still unable to get there. SelectedValueand SelectedTextare always undefined. Below is my code:

我是新手AngularJS并试图从Dropdown. 我遵循了很多教程,但仍然无法到达那里。SelectedValue并且SelectedText总是undefined。下面是我的代码:

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:

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", disabled: false },
   { id: 5, name: "Car & Motorcycle Equipment", disabled: false },
   { id: 6, name: "Boats", disabled: false },
   { id: 7, name: "Other Vehicles", disabled: false },
   { id: 8, name: "- House and Children -", disabled: true },
   { id: 9, name: "Appliances", disabled: false },
   { id: 10, name: "Inside", disabled: false },
   { id: 11, name: "Games and Clothing", disabled: false },
   { id: 12, name: "Garden", disabled: false }
];

$scope.onCategoryChange = function () {

    $window.alert("Selected Value: " + $scope.itemSelected.id + "\nSelected Text: " + $scope.itemSelected.name);

};
}]);

And one more thing, I have defined my first item as Select a category...then Why first item in Dropdown is always empty.

还有一件事,我已经将我的第一个项目定义为Select a category...为什么 Dropdown 中的第一个项目总是空的。

Below is my fiddle sample. http://jsfiddle.net/Qgmz7/136/

下面是我的小提琴样本。 http://jsfiddle.net/Qgmz7/136/

回答by Arkantos

That's because, your model itemSelectedcaptures the current value of your select drop down which is nothing but the valueattribute of your optionelement. You have

那是因为,您的模型itemSelected捕获了 select 下拉列表的当前值,它只是元素的value属性option。你有

<option ng-repeat="category in categories" value="{{category.id}}">

in your code, so in the rendered version, you'll get

在你的代码中,所以在渲染版本中,你会得到

<option ng-repeat="category in categories" value="0">

but you're expecting itemSelectedto be your category object and any attempt to query idor other property will return undefined.

但您希望itemSelected成为您的类别对象,任何查询id或其他属性的尝试都将返回undefined.

You can use ng-optionswith group bywith little bit of change to your data or you can use normal ng-repeat, get the selectedIndex and lookup the category object from your categories list using that index. Showcasing the first approach here.

您可以使用ng-optionswithgroup by对数据稍作更改,也可以使用 normal ng-repeat,获取 selectedIndex 并使用该索引从类别列表中查找类别对象。在这里展示第一种方法。

HTML

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>

Updated Data

更新数据

$scope.categories = [
       { id: 0, name: "Select a category..."},
       { id: 1, name: "Cars", group : "- Vehicles -" },
       { id: 2, name: "Commercial vehicles", group : "- Vehicles -" },
       { id: 3, name: "Motorcycles", group : "- Vehicles -" }
 ];

 $scope.itemSelected = $scope.categories[0];

Instead of disabled property, you can add a groupproperty which can be used in group by.

您可以添加一个group可以在group by.

Here' an updated Fiddleto illustrate the idea.

这是一个更新的小提琴来说明这个想法。

回答by Pankaj Parkar

You should use ng-optionsto set object to your ng-modelvalue on change of you select options.

您应该使用在更改选择选项时ng-options将对象设置为您的ng-model值。

Markup

标记

<select name="category-group" id="categoryGroup" class="form-control" 
  ng-model="itemSelected" ng-change="onCategoryChange(itemSelected)" 
  ng-options="category.name for category in categories">
    <option value="0">Select a category...</option>
</select>

Fiddle Here

在这里小提琴

Update

更新

For persisting style you have to use ng-repeatthere, in that case you will only have idbinded to your ng-modeland while retrieving whole object you need to filter your data.

对于持久化样式,您必须在ng-repeat那里使用,在这种情况下,您将只id绑定到您的ng-model对象,而在检索整个对象时,您需要过滤数据。

$scope.onCategoryChange = function () {
    var currentSelected = $filter('filter')($scope.categories, {id: $scope.itemSelected})[0]
    $window.alert("Selected Value: " + currentSelected.id + "\nSelected Text: " + currentSelected.name);
};

Updated Fiddle

更新的小提琴

回答by Jean Troiani

<div ng-app="SelectApp">
    <div ng-controller="selectController">
    <select ng-change='onCategoryChange()' ng-model="itemSelected" ng-options="category.name for category in categories">
        <option value="">-- category --</option>
    </select>
</div>

//http://jsbin.com/zajipe/edit?html,js,output

// http://jsbin.com/zajipe/edit?html,js,output

回答by ArBro

A little change in your onCategoryChange()should work:

onCategoryChange()应该工作的一点变化:

$scope.onCategoryChange = function () {
        $window.alert("Selected Value: " + $scope.categories[$scope.itemSelected - 1].id + "\nSelected Text: " + $scope.categories[$scope.itemSelected -1].name);

    };

JSFiddle: http://jsfiddle.net/Qgmz7/144/

JSFiddle:http: //jsfiddle.net/Qgmz7/144/

回答by tbutcaru

ngChangeonly returns the value of your selected option and that's why you don't get the whole data.

ngChange只返回您选择的选项的值,这就是为什么您没有获得全部数据的原因。

Here's a working solution without changing your markup logic.

这是一个无需更改标记逻辑的可行解决方案。

Markup:

标记:

<select
    name="category-group"
    id="categoryGroup"
    class="form-control"
    ng-model="id"     
    ng-change="onCategoryChange(id)">

ngChange handler:

ngChange 处理程序:

 $scope.onCategoryChange = function (id) {
        //get selected item data from categories
        var selectedIndex = $scope.categories.map(function(obj) { return obj.id; }).indexOf( parseInt(id) );
        var itemSelected = $scope.categories[selectedIndex];

        $window.alert("Selected Value: " + itemSelected.id + "\nSelected Text: " + itemSelected.name);

    };


Another solution (little bit dirty) would be to change only the valueof your options into something like this:

另一种解决方案(有点脏)是只将value您的选项更改为如下所示:

<option .... value="{{category.id}}|{{category.name}}">

...and inside your actual ngChange handler, just split the value to get all the values as an array:

...在您实际的 ngChange 处理程序中,只需拆分该值即可将所有值作为数组获取:

$scope.onCategoryChange = function (itemSelected) {
    $scope.itemSelected = itemSelected.split('|'); //string value to array
    $window.alert("Selected Value: " + $scope.itemSelected[0] + "\nSelected Text: " + $scope.itemSelected[1]);

};

回答by Praburam S

Here very Simple and easy code What I did

这里非常简单和容易的代码我做了什么

<div ng-app="myApp" ng-controller="myCtrl">
Select Person: 
<select ng-model="selectedData">
   <option ng-repeat="person in persons" value={{person.age}}>
         {{person.name}}
   </option>
</select>
<div ng-bind="selectedData">AGE:</DIV>
<br>
</div>


    <script>
    var app = angular.module('myApp', []);
    app.controller('myCtrl',myCtrlFn);
    function myCtrlFn($scope) {

    $scope.persons =[
        {'name': 'Prabu','age': 20},
        {'name': 'Ram','age': 24},
        {'name': 'S','age': 14},
        {'name': 'P','age': 15}
        ];
    }
    </script>