使用ng-select循环遍历数组对象的默认值

default value using ng-select loop through array of object

本文关键字:对象 默认值 数组 遍历 ng-select 循环 使用      更新时间:2023-09-26

现在选择是空白的,我认为angular默认添加了它。我想让默认值是美国,但我尝试了ng-selected="country.name == 'American'",它不工作吗?

我DOM

<select name="country" ng-model="user.country"
                  ng-options="country.name for country in country_list" >
              {{name}}
          </select>

http://jsbin.com/tocojojora/edit?html, css, js,控制台输出

你可以这样做,ng-init="value='American Samoa'"这会在下拉菜单中设置默认值

 <select ng-model="value" ng-init="value='American Samoa'"   ng-options="code.name as code.name for code in country_list">
 </select>

$scope.user = {country: $scope.country_list[4]};

在你的控制器中设置默认的用户国家(在你的html模板中减少逻辑)。

JSBin

你的代码不工作的原因是:

ng-options="country.name for country in country_list"

在我的理解中,这里的值将是{name: 'Afghanistan', code: 'AF'},而不是AfghanistanAF

你应该尝试这样做:

ng-options="country.code as country.name for country in country_list"

这里的值是AF,你可以使用ng-init将其设置为

user.country = 'AS'

样本小提琴。

use something like this in your controller
$scope.user = {country:"American"}; //Default value to dropdown