简体   繁体   English

如何从angular的下拉列表中获取值?

[英]How to get the value from a dropdown in angular?

I am trying to get the value that user selects from my dropdown. 我试图获取用户从我的下拉菜单中选择的值。 I have 我有

<select ng-model="item" ng-change="vm.getItem()">
  <option value="discount">Discount</option>
  <option value="{{::item}}"
          ng-repeat="item in vm.items"
          ng-bind="item.name"
  </option>
  </select>

In my controller 在我的控制器中

vm.getItem = function() {
    vm.pickedItem = //not sure what to do...
    //I need to get the select item 
    //please noted that the discount is a stand alone option value. I need to get     
    //that too if user selects it.
}

I don't want to use ng-option as it has some restriction that I don't need. 我不想使用ng-option因为它有一些我不需要的限制。 I was hoping to get it from just regular <option> tag. 我希望从常规的<option>标记中获取它。 Thanks for the help! 谢谢您的帮助!

I would recommend you to use ngOptions 我建议您使用ngOptions

Set up select element with proper model ie vm.pickedItem which can be directly used in controller, or you can pass it to your method like vm.getItem(vm.pickedItem) 使用适当的模型(即vm.pickedItem设置select元素,该模型可以直接在控制器中使用,也可以将其传递给vm.getItem(vm.pickedItem)类的方法

<select ng-model="vm.pickedItem" ng-change="vm.getItem(vm.pickedItem )">
    <option value="discount">Discount</option>
    <option value="{{::item}}"
          ng-repeat="item in vm.items"
          ng-bind="item.name">
    </option>
</select>
vm.getItem = function() {
    var selectedItem = vm.item; 
    ////vm.item is the bound variable to the dropdown's ng-model directive
}

If you really wanted to use the ng-change event in this scenario, then on your "getItem" event, you should access the model bound to the dropdown's ng-model called "item" as seen in your html markup. 如果您确实想在这种情况下使用ng-change事件,那么在您的“ getItem”事件上,您应该访问绑定到下拉列表的ng-model的模型,称为“ item”,如html标记所示。

you forgetting to alis your controller in your select 您忘记select控制器

<select ng-model="vm.item" ng-change="vm.getItem()">

In controller 在控制器中

vm.getItem = function() {
    console.log(vm.item)
   or
   console.log(this.item)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM