Pergunta

I am using AngularJS to generate a form for submitting arguments to a function. In order for this to work properly, I want the possible options for the second select element to depend upon the current value of the bound model on the first element.

For example, the options for the first element represent choosing between Days, Weeks, or Months as the units for a dataset that will be generated upon submission. The behavior I am trying to implement is that when a given value is selected in the first element, the options available for the second element are restricted to any unit that is smaller than or equivalent to the selected unit in the first element.

For example, if I were to select "Days" as a unit, the options available to me for selecting a grouping would be limited only to "Days". If I selected "Weeks" the available options would expand to "Days" and "Weeks" and for a selected unit of "Months" all 3 options would be available for the grouping.

Heres the relevant 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>

and the accompanying controller:

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) {
        //...
    };
});

The above code works well enough, but with one annoying bug. Considering the case when "Months" is selected for the units and "Weeks" is selected for the grouping, when the user then changes the selection for the units to a value that should not have "Weeks" as a valid option, such as "Days", the value of the $scope.groupby does not change, allowing the user to be able to submit what should otherwise be an invalid form.

Any suggestions for another way to go about this?

PS made a fiddle for ya http://jsfiddle.net/VCx4y/

Foi útil?

Solução

The simple fix will be add a watcher in the controller

$scope.$watch('unit', function(oldValue, newValue){
    $scope.groupby = 0;
});

Please refer to this answer for the explanation.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top