繁体   English   中英

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

[英]select default option in dropdown dependent in ANGULAR.JS

我有一个依存下拉列表,我选择一个国家。 如果选择了哥伦比亚,则我需要默认标记为“ 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>

也许我不了解我。 我需要一个加载第一个下拉列表的国家,例如哥伦比亚,并且这个国家一旦出现“ manizales”缺陷标记

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

一种选择是在国家/地区输入上使用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;
        }
    }
};

您只需要添加'defaultIndex':每个父元素为0, 此处为示例

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];

});

您可以使用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>

替换ng-model =“ selectedState”

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

您需要做的2件事:

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

2)重新排列json中的状态,以使默认状态为第一个状态。

这是一个有效的例子

您还可以扩展它以将默认值添加到国家列表或将默认布尔值添加到状态对象。

暂无
暂无

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

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