Search code examples
angularjsangularjs-filterangularjs-watch

AngularJS - 2 selects for a range of years. Options in second one have to be greater or equal than first one selected


I have 2 selects where I need to choose a range of years. The year of the second select has to be greater or equal than the first one. So if I select a year in the first select, the second select should change and show just the years greater or equal than the year selected in the first select.

This is what I have right now:

<div ng-app="">
    <div ng-controller="appCtrl">
        <select  id="id_year_1">
            <option ng-repeat="year in years1 | filter:dateRangeFilter1" value="{{year}}">{{year}}</option>
        </select>
        <select  id="id_year_2">
            <option ng-repeat="year in years2 | filter:dateRangeFilter2" value="{{year}}">{{year}}</option>
        </select>    
    </div>
</div>


angular.module('app', ['ngResource'])

function appCtrl($scope) {
    var years = [2010, 2011, 2012];
    $scope.years1 = years;
    $scope.years2 = years;
    $scope.year1 = years[0];
    $scope.year2 = years[years.length - 1];

    $scope.$watch('years1', function(value, oldValue) {
        $scope.dateRangeFilter2 = function (value) {
            return value >= $scope.year2;
        };
    });
    $scope.$watch('years2', function(value, oldValue) {
        $scope.dateRangeFilter1 = function (value) {
            return value <= $scope.year1;
        };
    });
}

I have it also in this fiddle: http://jsfiddle.net/d3sb4hky/

Thanks.


Solution

  • I cut down a bit of your code to begin with (jsfiddle). I'm sure it's not perfect yet usage-wise, but it is what you asked for. Maybe you could use a ng-change on the first select to update secondSelect? ($watch is overrated!)

    <div ng-app="">
    <div ng-controller="appCtrl">
        <select ng-model="firstSelect" >
            <option ng-repeat="year in years" value="{{year}}">{{year}}</option>
        </select>
        <select ng-model="secondSelect">
            <option ng-if="year >= firstSelect" ng-repeat="year in years" value="{{year}}">
                {{year}}
            </option>
        </select>    
    </div>
    </div>
    
    // Script
    angular.module('app', ['ngResource'])
    function appCtrl($scope) {
        $scope.years = [2010, 2011, 2012];
    }