我使用AngularJS生成一个表单,用于向函数提交参数。为了使其正常工作,我希望第二个select元素的可能选项取决于第一个元素上绑定模型的当前值。
例如,第一个元素的选项表示在天、周或月之间进行选择,作为提交时将生成的数据集的单位。我试图实现的行为是,当在第一个元素中选择给定的值时,第二个元素可用的选项被限制为小于或等于第一个元素的所选单元的任何单元。
例如,如果我选择"天数"作为一个单位,则可用于选择分组的选项将仅限于"天数"。如果我选择了"周",可用选项将扩展为"天"one_answers"周"。对于选定的"月"单位,所有3个选项都可用于分组。
以下是相关的html:
<div ng-app="app">
<form ng-submit="generate(unit, groupby)" ng-controller="AppCtrl">View from the last:
<select class="form-control" ng-model="range" ng-options="r for r in ranges"></select>
<select class="form-control" ng-model="unit" ng-options="(units.indexOf(u)) as u + '(s)' for u in units"></select>Grouped by:
<select class="form-control" ng-model="groupby" ng-options="units.slice(0, unit + 1).indexOf(g) as g for g in units.slice(0, unit + 1)"></select>
<input type="submit" value="Get Data" />
</form>
</div>
以及附带的控制器:
app = angular.module('app', []);
app.controller('AppCtrl', function AppCtrl($scope, $http) {
$scope.ranges = [1, 2, 3, 4, 5, 6];
$scope.range = 3;
// options for time units
$scope.units = ["Day", "Week", "Month"];
// selected unit
$scope.unit = 0;
// selected grouping
$scope.groupby = 0;
// bound to form submit
$scope.generate = function (unit, groupby) {
//...
};
});
上面的代码运行得很好,但有一个烦人的错误。考虑到为单位选择"月"和为分组选择"周"的情况,当用户将单位的选择更改为不应将"周"作为有效选项的值(如"天")时,$scope.groupby的值不会更改,从而允许用户提交本应无效的表单。
有没有其他方法的建议?
PS为你做了一把小提琴http://jsfiddle.net/VCx4y/
简单的修复方法是在控制器中添加一个观察程序
$scope.$watch('unit', function(oldValue, newValue){
$scope.groupby = 0;
});
请参考此答案进行解释。