gpt4 book ai didi

javascript - 如何摆脱依赖选择的默认值?

转载 作者:行者123 更新时间:2023-11-30 12:53:09 25 4
gpt4 key购买 nike

我正在研究一对内容相互关联的组合。

HTML

 <span>{{lblRegion}}</span>
<select ng-model="currentRegion"
ng-options="region.name for region in regions"
ng-change="checkAll()">
</select>


<span>{{lblCountry}}</span>
<select ng-model="currentCountry"
ng-options="country.name for country in currentRegion.countries"
ng-disabled="currentRegion.id===0">
</select>

JS

$scope.regions = regions;
$scope.currentRegion = regions[0];
$scope.currentCountry = $scope.currentRegion.countries[0];

$scope.checkAll = function() {

if (currentRegion.id !== 0) {
$scope.test = true;
} else {
$scope.test = false;
}
}

var regions = [{
'id': 0,
'name': 'All',
'countries': [{
'id': '0',
'name': 'All'

}]
},
...

行为必须满足:

  1. 两种组合都有“全部”选项。
  2. “地区”组合的内容设置了“国家”组合的可能值。
  3. 如果区域组合设置为“全部”,国家/地区组合将被禁用,其内容为选项“全部”。

我想摆脱总是出现在国家/地区组合中的空默认选项。我读过 ng-init 可以完成这项工作,但是 ng-init docs指出不应以这种方式管理此问题。

如何删除空选项?

最佳答案

由于第二个 ng-option 取决于 currentCountry.countries,因此选择了默认的 blank 值,并且值currentRegion,即 regions[0].countries[0],不在此列表中。这可以通过在 currentRegion 更改后立即将 currentRegion 的值设置为 currentRegion.countries[0] 来纠正。

正如您所尝试的,这可以在 ng-change 中完成。

但是,我不信任 ng-changeng-model 的顺序。因此,我更愿意为任务设置 watch :http://plnkr.co/edit/TnHC039Hg7x0Oj9DmEkk?p=preview

Controller

$scope.$watch('currentRegion', function (newVal) {
if (typeof newVal !== 'undefined') {
$scope.currentCountry = newVal.countries[0];
}
})

模板

  <!-- Without ng-change -->
<select ng-model="currentRegion" ng-options="region.name for region in regions"></select>

关于javascript - 如何摆脱依赖选择的默认值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20275446/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com