当 ng-model 和 ng-options 引用不同的对象时,如何使用 ng-init 在选择框中选择默认值

How to use ng-init to select a default value in a select box when the ng-model and the ng-options are referencing different objects

本文关键字:选择 ng-init 何使用 默认值 ng-options ng-model 引用 对象      更新时间:2023-09-26

我有一个迭代listOfThings的选择框,并且模型具有currentThing属性。选择框将正确绑定到currentThing

但是,我无法ng-init将默认值设置为 listOfThings currentThing .以下内容未设置默认值。

 <select ng-options = "someThing as someThing.name for someThing in controller.listOfThings"
                                ng-model = "controller.currentThing"
                                ng-init = "someThing = controller.currentThing"
                                ng-change = "controller.changeThing(controller.currentThing)"/>

我输出 someThingcurrentThing 的值,它们是相同的。

有什么想法吗?谢谢!

与其在 DOM 中使用,不如在控制器中分配默认值

喜欢:

$scopr.controller.currentThing = $scopr.controller.listOfThings[0];// first element or as your need

然后就不需要了

ng-init = "someThing = controller.currentThing"