如何在包含ng-repeat的选择上触发ng-change

时间:2013-04-21 15:49:12

标签: angularjs angularjs-ng-repeat

我有两个选择框,当第一个选择框改变时,第二个选择框会自动更新。

<label>Region</label>
<select ng-model="region" 
        ng-change="clear(1)" 
        ng-options="l.region for l in locations"
></select>
<br />
<label>Country</label>
<select ng-model='country'
        ng-change="clear(2)" 
        ng-options="c.country for c in region.countries"
></select>

我的位置是一个json对象,如下所示:

[
  {region: "Europe", countries: [{country: "France"}, {country: "UK"}/*, ...*/]},
  {region: "Africa", countries: [{country: "Cameroon"}, {country: "Algeria"}]}
  /*, ...*/
]

这一切都很好。

当我想将第一个选择框的值设置为欧洲时,它开始变得复杂,我想在第二个选择框上触发ng-change事件。

有关如何做到这一点的任何想法?

2 个答案:

答案 0 :(得分:5)

您希望在第二个选择框上触发ng-change事件,这相当于模型region更改时的情况。所以你可以使用观察者来实现它。

$scope.$watch('region', function (newValue, oldValue) {
    console.log(newValue, oldValue);
})

答案 1 :(得分:1)

当您只需从控制器手动调用该函数时,为什么要触发onchange事件?另外,请不要忘记您可以手动设置在ng-model中指定的属性值,并且其值将反映在select元素中。

相关问题