我使用外部json文件填充我的选择。一切正常。但是如何设置我的选择的默认值? 我想将它设置为“United States”,这是我的选项值之一,它是从json-files countries.json加载的。
我试过这样做:
ng-init="selectionCountry = options['United States']
或带有号码,因为各州处于第一位......
ng-init="selectionCountry = options[0]
但是,它不起作用。有什么提示吗?
HTML
<select id="country" class="form-control country" ng-model="selectionCountry">
<option value="" ng-options="country in data.locations.countries | orderBy:'name'">{{country.name}}</option>
</select>
SCRIPT
.controller('NewInvoiceCtrl', ['$scope', '$translate', '$modal', '$window', '$filter', '$http', '$timeout',
function($scope, $translate, $modal, $window, $filter, $http, $timeout) {
// load and populate Json in country select
$scope.data = {
"locations": {}
};
$http.get('l10n/countries.json')
.then(function(res) {
$scope.data.locations.countries = res.data;
$scope.$$phase || $scope.$apply();
// set default
$scope.selectionCountry = $scope.data.locations.countries[1];
});
}])
示例JSON
{
"alpha2": "US",
"alpha3": "USA",
"countryCallingCodes": [
"+1"
],
"currencies": [
"USD"
],
"ioc": "USA",
"name": "United States",
"status": "assigned"
},
答案 0 :(得分:1)
您可以使用ngOptions
指令并在控制器中运行orderBy
过滤器:
<强> HTML 强>
<select id="country" class="form-control country" ng-disabled="!data.locations.countries.$resolved" ng-model="selectionCountry" ng-options="country.name for country in data.locations.countries">
</select>
<强>控制器强>
controller("NewInvoiceCtrl", function ($scope, $http, $filter) {
$scope.data = {
locations: {
countries: []
}
};
$scope.data.locations.countries.$resolved = false;
$http.get('countries.json').success(function(countries) {
$scope.data.locations.countries.length = 0;
Array.prototype.push.apply($scope.data.locations.countries, $filter('orderBy')(countries, 'name'));
$scope.selectionCountry || ($scope.selectionCountry = $scope.data.locations.countries[1]);
$scope.data.locations.countries.$resolved = true;
});
});
此外,添加$resolved
字段可以禁用该字段,直到填充了国家/地区列表(这类似于$resource
所做的那样)。
以下是一个有效的例子:http://plnkr.co/edit/vuKsqU5q52s7pfOPcGLI?p=preview
或者,如果要根据名称选择默认值:
$scope.data.locations.countries.$default = 'United States';
// when setting $scope.selectionCountry
$scope.selectionCountry = $filter('filter')($scope.data.locations.countries, {name: $scope.data.locations.countries.$default})[0];
以下是“按名称”过滤器的示例:http://plnkr.co/edit/Czy53cTfptPdyAPBr3eS?p=preview
答案 1 :(得分:0)
看起来这应该有效。我不确定你为什么打电话给$scope.$apply()
$http.get('l10n/countries.json')
.then(function(res) {
$scope.data.locations.countries = res.data;
$scope.selectionCountry = $scope.data.locations.countries[0];
});