简体   繁体   English

ngOptions尝试将资源响应用作所选项目时的行为异常

[英]ngOptions weird behavior when trying to use resource response as selected item

I tried to solve this over an hour, haven't found anything online. 我试图解决一个多小时的问题,却没有在网上找到任何东西。 This is the template: 这是模板:

        <select
          ng-model="user.platform_id"
          ng-options="platform.id as platform.title for platform in platforms"
          id="platform_id" class="form-control">
        </select>

and this is the controller : 这是控制器:

$scope.platforms = platformsEntity.query();
// Resource object coming from UI Router resolve, already fetched with user info
$scope.user = userEntity; 

the platforms resource response return the following format: 平台资源响应返回以下格式:

[ { id: 4, title: 'platform1'}, { id: 5, title: 'platform2' ]

the user is same, resource object with platform ID 用户相同,资源对象与平台ID

{ id: 3, name: 'foo', platform_id: 5 }

This way I can see all the platforms in the select box but it's not getting selected by the ngModel value (user.platform_id) The thing is that when I use plain object instead of resource: 这样,我可以在选择框中看到所有平台,但是没有被ngModel值(user.platform_id)选中。问题是,当我使用普通对象而不是资源时:

$scope.platforms = platformsEntity.query();
$scope.user = { platform_id: 5 } ; 

It is getting selected correctly ... 正在正确选择它...

Update 更新

i replicated the behavior i am looking for in ng-repeat: 我复制了我在ng-repeat中寻找的行为:

<select ng-model="user.platform_id" id="platform_id" class="form-control">
    <option 
        value="{{ platform.id }}" 
        ng-selected="user.platform_id == platform.id" 
        ng-repeat="platform in platforms"
    >{{ platform.title }}</option>
</select>

It's not about using a resource, the problem with programmatic selection of ng-options is that the ng-model value should refer to the same object as in the ng-options. 这与使用资源无关,而是以编程方式选择ng-options的问题在于ng-model值应引用与ng-options中相同的对象。 In order to initialize the selection, first make sure that the platforms array is populated (query might be async?), then loop through them, and set the id object of the platform of your choice as the platform_id object of the user. 为了初始化选择,首先确保已填充platform数组(查询可能是异步的吗?),然后遍历它们,并将所选平台的id对象设置为用户的platform_id对象。

Try something like this. 尝试这样的事情。 Tell angular what you want to track the value by. 告诉angular您要track value的内容。

<select
      ng-model="user.platform_id"
      ng-options="platform.title for platform in platforms track by platform.id"
      id="platform_id" class="form-control">
</select>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM