3

我有一个这样的选择框:

    <select class="form-control"
            ng-model="contactName"
            ng-change="testFun(contactName)"
            ng-options="contact.Id as contact.Name + ' ' + contact.Surname for contact in company.items.contacts"
            ng-selected="$scope.contactId === contact.Id">
    </select>

其中 $scope.contactId = 14151 和 contact.Id = 14151

但是选择框仍然没有选择正确的人 en 仍然显示为空白。

我无法弄清楚我在这里做错了什么。

编辑

<select class="form-control" 
        ng-model="contactName"
        ng-change="testFun(contactName)"
        ng-options="contact.Id as contact.Name + ' ' + contact.Surname + ' id:' + contact.Id for contact in company.items.contacts"
        ng-selected="contactId == contact.Id">
 </select>
 <pre>
    contactId: {{contactId}}
 </pre>

这会导致以下结果,这也证实了 ID 是相同的: ContactId Option with the same ID

盒子仍然是空白的

4

2 回答 2

2

来自 AngularJS文档

注意:ngSelected 不与 select 和 ngModel 指令交互,它只在元素上设置 selected 属性。如果您在选择上使用 ngModel,则不应在选项上使用 ngSelected,因为 ngModel 将设置选择值和选定选项。

话虽如此,您应该ng-init="contactName = contactId"按照@Noman 的建议使用,它使用 初始化contactName变量,contactId随后选择正确的选项。

于 2017-08-14T14:23:12.407 回答
1

使用ng-init这将起作用。你不能$scope在 html 里面使用。删除$scope会工作。

<select class="form-control"
        ng-model="contactName"
        ng-change="testFun(contactName)"
        ng-options="contact.Id as contact.Name + ' ' + contact.Surname for contact in company.items.contacts"
        ng-init="contactName = contactId" >
</select>

ngSelected不适用于您必须使用的ngOptionsng-init

于 2017-08-14T14:01:52.173 回答