【发布时间】:2016-11-16 07:26:26
【问题描述】:
我有以下选择,其中包含世界上所有国家/地区,我有一个 Angularjs 控制器,它调用一个方法,该方法向我返回其中一个国家/地区的 idCountry,其中变量 idCountry 是对象而不是该对象在选择中的位置索引。
我需要使用idCountry在select中预先选择那个国家,有没有办法使用对象的id来获取这个对象在select中的索引,我读了一些文章说这可以在 ng-options 表达式中使用 track by 完成,但我不知道如何。
如果我设法获得索引,我可以预先选择这样的选项
$scope.countriesSelect = $scope.countriesSelect[put here the select index that I can find]
这是我的选择
<select name="selectCountries" class="form-control"
id="selectCountries"
ng-model="selectCountries"
ng-options="country.name for country in countryList track by country.idCountry"
ng-change=""
required>
</select>
这就是我在控制器中尝试做的事情
var idCountry = id;
$scope.selectCountries= $scope.selectCountries[idCountry]
编辑
我编辑了我的代码,我读过类似的问题,但大多数问题都是关于如何使用默认值初始化选择,我正在尝试做一个编辑页面,用户可以在其中检查他输入的所有值在他注册期间,他可以编辑它们,所以这个选择需要用他选择的值初始化。
我可以得到对象列表中任何对象的id
这是填充我的选择的对象列表
[{idCountry: 2, name: countryName}, {idCountry: 4, name: AnothercountryName}, {idCountry: 7, name: rockyCOuntry}]
我有一个方法可以返回idCountry,我想知道是否有办法使用这个idCountry 获取选择的索引
或者在我的ng-options 表达式中加入一些表达式,比如使用track by 或其他东西。
我试过这个$scope.selectCountries= $scope.selectCountries[idCountry]
但是,如果我输入7 而不是在rockyCOuntry 中设置选择,而是在另一个国家/地区设置选择,这不会返回正确的国家/地区,我相信这是因为列表对象的ID 与相同的索引不对应占据该对象的选择。
【问题讨论】:
-
不应该 ng-model="selectCountries" 是 ng-model="countriesSelect" 吗?
-
这里有很多类似的问题......包括在本页右侧的相关中。您的 ng-options 仅选择 name , ng-model 也不匹配控制器,并且您正在控制器中设置对象。不知道你想要什么
-
@charlietfl 我编辑了我的问题
标签: javascript angularjs select angularjs-directive angularjs-ng-options