我正在使用AngularJS生成用於向函數提交參數的表單。爲了使其正常工作,我希望第二個select元素的可能選項取決於第一個元素上綁定模型的當前值。AngularJS選擇:基於當前表單狀態限制ngOptions
例如,第一個元素的選項表示在Days,Weeks或Months之間選擇作爲提交時將生成的數據集的單位。我試圖實現的行爲是,當在第一個元素中選擇給定值時,第二個元素的可用選項限制爲小於或等於第一個元素中所選單元的任何單位。
例如,如果我選擇「天數」作爲單位,則可用於選擇分組的選項僅限於「天數」。如果我選擇「星期」,則可用選項將擴展爲「天」和「星期」,對於選定單位的「月」,所有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/
好吧,我曾考慮過這個問題,但是想知道是否我不能直接用已經寫入控制器的東西修復它,謝謝! –