繁体   English   中英

如何预先选择Angularjs中的选择选项,该选项填充了ng-options

[英]How to pre-select a select option in an Angularjs select that's filled with ng-options

我有以下的选择充满了世界上所有的国家,我有一个Angularjs控制器调用返回我的方法idCountry的国家之一,该变量idCountry是对象的ID,而不是的索引对象在select中的位置。

我需要使用idCountry在select中预先选择那个国家,是否有办法使用对象的id获取此对象在select中的索引,我读了一些文章说这可以使用track by在ng-options表达式但我不知道如何。

如果我设法得到索引,我可以预先选择这样的选项

$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获取select的索引,或者在我的ng-options表达式中添加一些表达式,比如使用track by或者其他东西。

我试过这个$scope.selectCountries= $scope.selectCountries[idCountry]但是这并没有给我正确的国家,如果我把7而不是在rockyCOuntry中设置选择它在另一个国家设置选择,我相信这是因为list对象的id与占用该对象的select的相同索引不对应。

好吧,请记住你的ng-model实际上是一个object ,所以你不能直接设置<option>countryId 为了实现你想要的,你已经拥有了id ,你必须在你的控制器中做这样的事情:

var selectedId = 7; // Just an example

$scope.selectCountries = { "idCountry": selectedId };    

另一方面,如果您不想在ngModel设置整个object ,只需要idCountry (我不推荐),您可以执行以下操作:

$scope.selectCountries = 7; // Just an example

<select name="selectCountries" class="form-control" id="selectCountries" ng-model="selectCountries" ng-options="country.idCountry as country.name for country in countryList" required>
 </select>

演示:

 (function() { "use strict"; angular.module('app', []) .controller('mainCtrl', function($scope) { $scope.countryList = [ { "idCountry":2, "name":"countryName" }, { "idCountry":4, "name":"AnothercountryName" }, { "idCountry":7, "name":"rockyCOuntry" } ]; $scope.selectCountries = { "idCountry": 7 }; // $scope.selectCountries = 7; }); })(); 
 <!DOCTYPE html> <html ng-app="app"> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script> </head> <body ng-controller="mainCtrl"> <select name="selectCountries" class="form-control" id="selectCountries.id" ng-model="selectCountries" ng-options="country.name for country in countryList track by country.idCountry" required> </select> <pre ng-bind="selectCountries | json"></pre> </body> </html> 

注意:两种方式都可以获得预期的结果。

我希望它有所帮助。

暂无
暂无

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

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