选择依赖于ANGULAR.JS的下拉列表中的默认选项

时间:2016-05-18 15:36:45

标签: javascript angularjs

我有依赖下拉列表我选择了一个国家/地区。我需要默认标记" manizales"如果哥伦比亚被选中,"芝加哥"如果选择美国(美国),则标记。我尝试了很多东西,但不知道如何第一次标记默认选项。

<select id="country" ng-model="selectedCountry" ng-options="country.id as country.name for country  in countries track by country.id">
    <option value="">Choose</option>
</select>Departement:
<select id="state" 
ng-model="selectedState" ng-options="state.id as state.dep for state in ((countries | filter:{'id':selectedCountry})[0].states) track by state.id">
    <option value="">Choose</option>
</select>
也许我不理解我。当第一个下拉列表出现时,我需要一个国家,例如哥伦比亚,并且一旦标记为&#34; manizales&#34;缺陷

http://plnkr.co/edit/6gvGmfqIqEAyYtYyYIb8?p=preview

5 个答案:

答案 0 :(得分:1)

一种选择是在国家/地区输入上使用ng-change,并在更改时分配$scope.selectedState。我还建议为每个国家/地区添加defaultStateId属性,以使其更加灵活。

因此,您的国家/地区HTML将成为:

<select id="country" ng-change="CountrySelected()" ng-model="selectedCountry" ng-options="country.id as country.name for country  in countries track by country.id">
    <option value="">Choose</option>
</select>

您的CountrySelected函数看起来像这样:

$scope.CountrySelected = function() {
    var countryId = $scope.selectedCountry;
    for (var i = 0; i < $scope.countries.length; ++i) {
        var country = $scope.countries[i];
        if (country.id === countryId) {
            $scope.selectedState = country.defaultStateId;
            break;
        }
    }
};

答案 1 :(得分:1)

你只需要添加'defaultIndex':0 foreach父元素,example here

var Aplic = angular.module(“Aplic”,[]);

Aplic.controller('CountryCntrl',function($ scope){

$scope.countries = [{
    'id': '1',
    'name': "Colombia",
    'defaultIndex': 0,
    'states': [{
        'id': '12',
        'dep': "Manizales"
    }, {
        'id': '11',
        'dep': "Bogota"
    }]
}, {
    'id': '2',
    'name': "USA",
    'defaultIndex': 1,
    'states': [{
        'id': '3',
        'dep': "California"
    }, {
        'id': '15',
        'dep': "Chicago"
    }]
}];

$scope.selectedCountry = $scope.countries[0];

});

答案 2 :(得分:0)

您可以使用ng-change进行以下更改。 http://plnkr.co/edit/RUxVch?p=preview

<select id="country" ng-model="selectedCountry" ng-options="country as country.name for country  in countries" ng-change='selectedState = selectedCountry.states[0].id;'>
    <option value="">Choose</option>
</select>Departement:
<select id="state" 
ng-model="selectedState" 
ng-options="state.id as state.dep for state in selectedCountry.states">
    <option value="">Choose</option>
</select>

答案 3 :(得分:0)

替换 ng-model =“selectedState”

以下代码 ng-model =“(countries | filter:{'id':selectedCountry})[0] .states [0]”

答案 4 :(得分:0)

你需要做的两件事:

1)在ng-change下拉列表中添加selectedCountry,将selectedState模型设置为列表中的第一个状态

2)重新安排你的json中的状态,以便默认状态是第一个。

Here is a working example

您还可以对其进行扩展,以将默认值添加到国家/地区列表或州状态对象的默认布尔值。

相关问题