Angular默认选择选项 [英] Angular default select option

查看:58
本文介绍了Angular默认选择选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在选择正确设置数据的默认选项时遇到问题.我正在通过Ajax调用从服务器获取数据.然后,我希望能够使用表单来编辑此数据.我想指出选择以使用在控制器对象中设置的选项,但是当您编辑选择时,我希望模型指向ajax数据,因为那是我写回服务器的内容.如您在我的plunkr中所看到的,四个项目中的每个项目都应填写其选择选项,但所有选择都开始为空.

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

在有关角度的官方文档中,他们说要执行以下操作来设置默认值:

In the official documentation for angular they say to do the following to set the default:

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>

在我的情况下,这些选项不在ajax数据中,而仅是当前选择的选项.所以我想通过控制器对象管理可用选项,但将选择绑定到ajax数据.谢谢.

In my case the options aren't in the ajax data however, only the currently selected option. So I want to manage available options via a controller object but bind the select to the ajax data. Thanks.

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

推荐答案

您应定义要绑定到"option"的哪个属性:

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>

正在运行的演示 https://plnkr.co/edit/BezGaYjykfQrFQ9nZop2?p=preview

这篇关于Angular默认选择选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆