简体   繁体   English

角度:选定值未保留在由ng-options生成的select中

[英]Angular: selected value not maintained in select generated with ng-options

I have a dropdown generated using ng-options 我有一个使用ng-options生成的下拉列表

<select class="form-control"  ng-options="item.value as item.label for item in filterFields track by item.value" ng-model="selectedFilterField">
</select>

The problem is that when I select an option from this dropwon, the selected item appears as empty and an extra blank element is added to the dropdown. 问题是,当我从该下拉菜单中选择一个选项时,所选项目显示为空,并且在下拉菜单中添加了一个额外的空白元素。 What am I doing wrong? 我究竟做错了什么?

Edit: added controller code: 编辑:添加了控制器代码:

$scope.columns = accountColumns; $ scope.columns = accountColumns;

    $scope.filterFields = [];

    $scope.filterFields.push(defaultSelectOption);
    $scope.filterFieldValues.push(defaultSelectOption);

    var idx = 1;

    for(i=0; i < accountColumns.length; i++) {
        var option = {label: accountColumns[i], value: accountColumns[i]};
        $scope.filterFields.push(option);
    }
    $scope.selectedFilterField = $scope.filterFields[0];

Let's say your filterFields array has objects that look like this: 假设您的filterFields数组具有如下对象:

{
    name: "",
    value: 0
}

In your ng-options you tell angular that the possible values for the select is an array of these objects. 在ng-options中,您告诉angular选择的可能值是这些对象的数组。 But you also tell angular that when you select an option then the real value is the object.value; 但是,您还告诉angular,当您选择一个选项时,实际值就是object.value;。 So now angular sees that this value is not present in the array of options and tries to add it or something. 因此,现在angular看到此值不存在于选项数组中,并尝试将其添加。

Initially the dropdown works because you set the ng-model to a complete object present in the filterFields array. 最初,下拉列表起作用是因为您将ng-model设置为filterFields数组中存在的完整对象。

Try it with this: 试试这个:

ng-options="item for item in filterFields track by item.value"

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

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