在Angular.js中-如何在下拉菜单中检查所选选项的值?
我有一个下拉菜单,旁边有一个加号按钮。
按下按钮会触发功能。如何“选择”进入变量?
({{selected}}在html中有效,但我希望在JS中使用此值)
> <select ng-options="key as key for (key, prop) in
> vm.schema.properties" ng-model="selected"">
> </select> //the dropdown
<p id="plusbutton"> //the add button
<div class="btn btn-info btn-sm" ng-model="selected" ng-click="vm.addMappingField()">
<span class="glyphicon glyphicon-plus"></span>
</div>
</p>
Javascript / Angular:
function addMappingField() {
var item = {{selected}}; //Here should be the value of the dropdown
vm.mappingFields.push({
destination: "item",
});
};
答案 0 :(得分:1)
您可以将所选模型作为addMappingField函数的参数传递,也可以直接在控制器中访问它,例如$scope.selected
<div class="btn btn-info btn-sm" ng-click="vm.addMappingField(selected)">
function addMappingField(selected) {
var item = selected //Here should be the value of the dropdown
vm.mappingFields.push({
destination: "item",
});
};
答案 1 :(得分:1)
首先,您要在两个不同的元素上将selected
设置为NgModel,仅应在select标记上设置它。
第二,将选定的模型连接到vm,然后在控制器的addMappingField()方法中引用它
查看
<select ng-options="key as key for (key, prop) in vm.schema.properties" ng-model="vm.selected"">
</select>
<p id="plusbutton">
<div class="btn btn-info btn-sm" ng-click="vm.addMappingField()">
<span class="glyphicon glyphicon-plus"></span>
</div>
</p>
控制器
function addMappingField() {
var item = vm.selected;
vm.mappingFields.push({
destination: "item",
});
};
答案 2 :(得分:0)
在dom中删除 ng-model =“ selected” 。
<div class="btn btn-info btn-sm" ng-click="vm.addMappingField()">
如果您将作用域用作vm,请确保在代码中进行了这些更改。
function addMappingField() {
var item = vm.selected //Here should be the value of the dropdown
vm.mappingFields.push({
destination: item,
});
};
如果在控制器中使用$scope
,则更改为
var item = $scope.selected