【问题标题】:Angularjs Dropdown OnChange Selected Text and ValueAngularjs Dropdown OnChange 选定的文本和值
【发布时间】:2017-09-29 19:08:18
【问题描述】:

我是 AngularJS 的新手,并试图从 Dropdown 获取选定的文本和值。我遵循了很多教程,但仍然无法到达那里。 SelectedValueSelectedText 始终是 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:

'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);

};
}]);

还有一件事,我将我的第一项定义为Select a category... 然后为什么下拉菜单中的第一项总是空的。

以下是我的小提琴示例。 http://jsfiddle.net/Qgmz7/136/

【问题讨论】:

    标签: javascript jquery html angularjs angularjs-ng-options


    【解决方案1】:

    那是因为,您的模型 itemSelected 捕获了您的选择下拉列表的当前值,这不过是您的 option 元素的 value 属性。你有

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

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

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

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

    您可以将ng-optionsgroup 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 -" },
           { id: 2, name: "Commercial vehicles", group : "- Vehicles -" },
           { id: 3, name: "Motorcycles", group : "- Vehicles -" }
     ];
    
     $scope.itemSelected = $scope.categories[0];
    

    您可以添加一个group 属性来代替禁用的属性,该属性可以在group by 中使用。

    这里有一个更新的Fiddle 来说明这个想法。

    【讨论】:

    • 此示例将在group by 子句在ng-options 呈现的选择元素中使用optgroup 保留组标题。希望这会有所帮助:)
    • 这是一个很好的解决方案,但为什么第一次下拉是空的。
    • 那是因为我们没有在控制器中为itemSelected 设置任何默认值。将您的默认值添加到您的类别列表并设置该值,如 here 所示
    • 非常感谢 Ankantos。非常好的解决方案和新的学习内容。 :)
    • 很高兴能帮上忙 :)
    【解决方案2】:

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

    标记

    <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

    更新

    对于持久化样式,您必须在那里使用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

    【讨论】:

    • 它有效,但我的 css 逻辑消失了。如果你看到我的样本。 - 车辆 - 和 - 房屋和儿童 - 被禁用并使用不同的 css。
    • @UsmanKhalid 看看更新的小提琴..它会按你的意愿工作
    • 非常感谢。它工作正常,但为什么第一次下拉是空的?
    【解决方案3】:
    <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

    【讨论】:

      【解决方案4】:

      对您的 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/

      【讨论】:

      • 你疯了吗..$scope.categories[$scope.itemSelected] 怎么会从categories 中选择一个值?
      • $scope.itemSelected 将返回选项列表中所选项目的值(作为数字)。通过将其传递给对象,您可以选择对象的 n 属性,您将可以访问数据。
      • 你能看看你的小提琴它显示错误的值作为它考虑的数组索引
      • 更新了代码。它现在应该输出正确的值。
      • 没有可能伤害的家伙..如果假设你已经跳过了一个/两个元素 id 然后拿了第三个..那么$scope.itemSelected - 1 将不起作用..
      【解决方案5】:

      ngChange 仅返回您选择的选项的值,这就是您无法获得全部数据的原因。

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

      标记:

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

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

      另一种解决方案(有点脏)是仅将您的选项中的value 更改为如下内容:

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

      ...在您的实际 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]);
      
      };
      

      【讨论】:

        【解决方案6】:

        这里很简单的代码我做了什么

        <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>
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2017-02-09
          • 2019-06-05
          • 2019-01-02
          • 1970-01-01
          • 2019-01-15
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多