[英]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.