简体   繁体   English

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

[英]default value using ng-select loop through array of object

For now the select is blank, I think angular added it by default. 目前,选择为空,我认为angular默认添加了它。 I want the default to be American, but I trid ng-selected="country.name == 'American'" it doesn't work? 我希望默认设置为American,但是我尝试ng-selected="country.name == 'American'"无效吗?

my DOM 我的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,console,output http://jsbin.com/tocojojora/edit?html,css,js,控制台,输出

You can do this, ng-init="value='American Samoa'" this will set the default value in dropdown 您可以执行此操作, 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>

DEMO 演示

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

Set the default user country in your controller(less logic in your html template). 在控制器中设置默认用户国家(在html模板中减少逻辑)。

JSBin 联合会

The reason your code was not working was because of this: 您的代码无法正常工作的原因是因为:

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

In my understanding, here value will be {name: 'Afghanistan', code: 'AF'} and not Afghanistan or AF . 根据我的理解,此处的值将是{name: 'Afghanistan', code: 'AF'}而不是AfghanistanAF

You should try something like this: 您应该尝试这样的事情:

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

Here value will AF and you can use ng-init to set it as 此处的值将为AF ,您可以使用ng-init将其设置为

user.country = 'AS'

Sample Fiddle . 样品小提琴

use something like this in your controller

$scope.user = {country:"American"}; //Default value to dropdown

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

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