【发布时间】:2016-09-16 13:06:28
【问题描述】:
谁能告诉我为什么选择了第一个示例中的模型选项,而第二个示例中没有选择普通数组:
// Plain old array
vm.owner = ['example', 'example2', 'example3', ...];
模特在哪里vm.model.address.owner = 2;
// EXAMPLE 1 - Works
// Force index to be a number: using id*1 instead of it being a string:
// and the option ('example3') is selected based on the model value of 2
// indicating the index
<select id="owner"
name="owner"
placeholder="Residential Status"
ng-model="vm.model.address.owner"
ng-required="true"
ng-options="id*1 as owner for (id, owner) in vm.owner">
<option value="">Select Value</option>
</select>
即使模型中仍然设置了值,也不会选择尝试不使用 hack 并使用 track by index 2。
// EXAMPLE 2 - Doesn't Work
// Markup doesn't show value to be a string: using track by, but the
// option set in the model doesn't cause the option to be selected it
// remains as the default with a value of ''
<select id="owner"
name="owner"
placeholder="Residential Status"
ng-model="vm.model.address.owner"
ng-required="true"
ng-options="owner for (id, owner) in vm.owner track by id">
<option value="">Select Value</option>
</select>
我发现 ngOptions 非常令人困惑,因此示例 2 的任何解释或解决方案都非常好,因为它更简洁且不是 hack。
【问题讨论】:
标签: angularjs ng-options angularjs-1.5