Angular js如何在没有ng-options的情况下使用JSON填充下拉列表

时间:2016-04-04 11:42:27

标签: angularjs

我以这种方式填充下拉并且数据即将到来,但是在第一次显示下拉列表时没有选择任何数据。这是我的代码。请看看我告诉我哪里弄错了。

<div ng-controller="DemoCtrl" ng-app="main">
<select ng-model="selectedCountry">
<option value="">Select Account</option>
<option ng-repeat="item in chooseCountries" value="item.countryId">
  {{item.countryId}}-{{item.name}}
</option>    
</select>  

<span>Selected country id is {{selectedCountry.countryId}}</span>   
</div>

var app = angular.module('main', []);
app.controller('DemoCtrl', function ($scope) {

    $scope.chooseCountries=[
        {countryId : 1, name : "France - Mainland", desc: "some description" },
        {countryId : 2, name : "Gibraltar", desc: "some description"},
        {countryId : 3, name : "Malta", desc: "some description"}
    ];

    $scope.selectedCountry = $scope.chooseCountries[0].countryId;
});

3 个答案:

答案 0 :(得分:2)

更好的方法是使用ng-options指令。

<select ng-model="selectedCountry" 
  ng-options="country.countryId as (country.name+'-'+country.desc) for country in chooseCountries">
</select>

Demo here

为什么ng-repeat方法不起作用?(仅供解释,不建议使用

您应该使用value正确填写选项countryId属性,例如value="{{item.countryId}}"

<select ng-model="selectedCountry">
   <option value="">Select Account</option>
  <option ng-repeat="item in chooseCountries" value="{{item.countryId}}">
    {{item.countryId}}-{{item.name}}
  </option>    
</select>  

但上述内容不适用于您的情况,因为您的countryId字段采用数字格式,当option将该值分配给value属性时,它会转换为string格式。因此,在初始加载时,您不会看到countryId被绑定到选择框。将会发生2==="2"不会true的比较,因此即使您在ng-model中提供了选择框,也不会选择值。

您可以找到问题plunkr here

因此,要修复它,您需要通过调用number方法将string值转换为toString值,如下所示

$scope.selectedCountry = $scope.chooseCountries[0].countryId.toString();

通过执行上述更改选择框确实在下拉列表中选择了提供的countryId值,因为比较发生为真"2"==="2"

这就是为什么使用ng-options会更好,这确实保留了值datatype。基本上他们在没有损害数据类型的情况下工作。

http://plnkr.co/edit/evQJAKvMnl4btz4BZeuP?p=preview

答案 1 :(得分:2)

<select ng-options="country as country.countryId+  ' (' + country.name + ')' for country in chooseCountries  ng-model="selectedCountry "></select>

参阅:https://docs.angularjs.org/api/ng/directive/ngOptions

答案 2 :(得分:0)

您应该使用ng-options,如下所示

<select ng-model="selectedCountry" ng-options="country.countryId as country.name for country in  chooseCountries"></select>
相关问题