如何在 ng-option 中设置预选值?
How to set preselected value in ng-option?
我有本应在下拉列表中 select 编辑的城市 ID,但我无法预先 select 它。我应该 select 它来自指令还是有任何其他方式?
<select ng-model="cityId" ng-options="city.name for city in cities"></select>
你需要为此使用 select as
部分,前提是 id
是相应的 属性 你会做的城市对象:
ng-options="city.id as city.name for city in cities"
否则您需要提供与 ng-model 相同的对象引用(数组中的城市对象)(如果不使用 track-by
)。
当使用 track-by
时,你会做:
ng-options="city.name for city in cities track by city.id"
并将模型设置为:
$scope.cityId = {id:'CITY1'};
当使用 track by 时,您无需担心对象引用,它实际上将具有 属性 选项的值,反映确切的 id(不像 select as
保留带有索引的内部映射).这在进行表单发布时很有用。但是你应该注意不要将它与 select as
混用,因为两者的目的不同并且实现相互冲突。
将您的 ng-options 编辑为:
city.id as city.name for city in cities
如果您获取城市但不知道 ID
您可以在 javascript 成功功能(returns 个城市)中说:
$scope.cityId = the_cities[0].ID
将第一个设置为选中
否则你可以说:
$scope.cityId = 1; //or anything that exists
我有本应在下拉列表中 select 编辑的城市 ID,但我无法预先 select 它。我应该 select 它来自指令还是有任何其他方式?
<select ng-model="cityId" ng-options="city.name for city in cities"></select>
你需要为此使用 select as
部分,前提是 id
是相应的 属性 你会做的城市对象:
ng-options="city.id as city.name for city in cities"
否则您需要提供与 ng-model 相同的对象引用(数组中的城市对象)(如果不使用 track-by
)。
当使用 track-by
时,你会做:
ng-options="city.name for city in cities track by city.id"
并将模型设置为:
$scope.cityId = {id:'CITY1'};
当使用 track by 时,您无需担心对象引用,它实际上将具有 属性 选项的值,反映确切的 id(不像 select as
保留带有索引的内部映射).这在进行表单发布时很有用。但是你应该注意不要将它与 select as
混用,因为两者的目的不同并且实现相互冲突。
将您的 ng-options 编辑为:
city.id as city.name for city in cities
如果您获取城市但不知道 ID 您可以在 javascript 成功功能(returns 个城市)中说:
$scope.cityId = the_cities[0].ID
将第一个设置为选中 否则你可以说:
$scope.cityId = 1; //or anything that exists