为什么此代码无法正常工作?我希望在选择中选择中国,但它为空。
<div ng-app="app">
<div ng-controller="appController" class="p-2" ng-init="init()">
<select
name="user_country"
class="form-control"
ng-model="country"
ng-options="item.id as item.title for item in countries track by item.id">
<option value="" disabled>Select Country</option>
</select>
</div>
</div>
控制器:
var app = angular.module('app', []).controller('appController', ['$scope', function($scope){
$scope.country = 3
$scope.countries = [
{id: 1, title: 'US'},
{id: 2, title: 'Japan'},
{id: 3, title: 'China'},
{id: 4, title: 'Russia'}
]
}])
我希望看到中国而不是一片空白。这是CodePen示例https://codepen.io/grinev/pen/YJERvz。
答案 0 :(得分:1)
将ng-options
修改为
ng-options="item.id as item.title for item in countries">
答案
没有track By
-invoking a browser with an intent
带有track By
-JSFiddle
track by
仅在内部帮助Angular进行数组排序。选项的值由第一个参数(在您的情况下为项目)定义。如果您希望按ID填写,则应使用item.id as item.name for item in items
答案 1 :(得分:0)
您需要存储对象,而不是ID。因此,您需要将其放置在countrys数组之后并将其设置为$scope.country = 3;
$scope.country = $scope.countries[2];