简体   繁体   English

角度默认选择选项

[英]Angular default select option

I am having a problem getting my select to properly set the default option for my data. 我在选择正确设置数据的默认选项时遇到问题。 I am fetching data from a server through an Ajax call. 我正在通过Ajax调用从服务器获取数据。 I then want to be able to edit this data using a form. 然后,我希望能够使用表单来编辑此数据。 I want to point the select to use options set in a controller object but when you edit the select I want the model to point to the ajax data because that is what I write back to the server. 我想指出选择以使用在控制器对象中设置的选项,但是当您编辑选择时,我希望模型指向ajax数据,因为那是我写回服务器的内容。 As you can see in my plunkr each of the four items should have their select options filled in but instead all of the selects start empty. 如您在我的plunkr中所看到的,四个项目中的每一个都应填写其选择选项,但所有选择都开始为空。

In the official documentation for angular they say to do the following to set the default: 他们在angular的官方文档中说要执行以下操作来设置默认值:

angular.module('defaultValueSelect', [])
  .controller('ExampleController', ['$scope', function($scope) {
  $scope.data = {
  availableOptions: [
    {id: '1', name: 'Option A'},
    {id: '2', name: 'Option B'},
    {id: '3', name: 'Option C'}
  ],
  selectedOption: {id: '3', name: 'Option C'} //This sets the default value of the select in the ui
  };
}]);

//Then in the HTML file:
<select name="mySelect" id="mySelect"
  ng-options="option.name for option in data.availableOptions track by option.id"
  ng-model="data.selectedOption"></select>

In my case the options aren't in the ajax data however, only the currently selected option. 就我而言,这些选项不在ajax数据中,而仅是当前选择的选项。 So I want to manage available options via a controller object but bind the select to the ajax data. 所以我想通过控制器对象管理可用选项,但将选择绑定到ajax数据。 Thanks. 谢谢。

https://plnkr.co/edit/Q16QLT?p=preview https://plnkr.co/edit/Q16QLT?p=preview

You should define which property of "option" you want to bind to: 您应该定义要绑定到“选项”的哪个属性:

<select ng-options="option.value as option.text for option in options" ng-model="item.select"></select>

Working demo https://plnkr.co/edit/BezGaYjykfQrFQ9nZop2?p=preview 工作演示https://plnkr.co/edit/BezGaYjykfQrFQ9nZop2?p=preview

将您的选择更改为此:

<select ng-options="option.text as option.text for option in options" ng-model="item.select"></select>

This will definately work: 一定可以正常工作:

Since your ng-model contains the full option object you need to bind it with the object in ng-options as well 由于您的ng-model包含完整选项对象,因此您还需要将其与ng-options中的对象绑定

<select name="mySelect" id="mySelect"
  ng-options="option as option.name for option in data.availableOptions track by option.id"
  ng-model="data.selectedOption"></select>

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

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