出生日期使用ng-options下拉

时间:2014-02-07 12:23:45

标签: javascript angularjs

我一直在尝试使用ng-options创建DOB下拉列表。我有一些如何创造它为白天&一个月,但在创造一年的问题时,我面临的问题是,我的下拉菜单以相反的顺序正确显示年份,即从2014年至1915年开始,但价值属性显示的值从1到100而不是2014 - 1915年。你能否建议更好这样做的方式。我发现这种方式很少蹩脚。我不想使用ng-repeat

HTML

<select class="day" id="DateOfBirth_Day" name="DateOfBirthDay" required ng-pattern="\d+" ng-model="user.question5.answer.dobday" ng-options="o for o in days">
    <option value="DD">DD</option>
</select>
<select class="month" id="DateOfBirth_Month" name="DateOfBirthMonth" required ng-pattern="\d+" ng-model="user.question5.answer.dobmonth" ng-options="o for o in months">
    <option value="MM">MM</option>
</select>
<select class="year" id="DateOfBirth_Year" name="DateOfBirthYear" required ng-pattern="\d+" ng-model="user.question5.answer.dobyear" ng-options="o for o in years">
    <option value="YYYY">YYYY</option>
</select>

控制器代码

 $scope.user = {
     question5: {
        answer: {
            dobday: 'DD',
            dobmonth: 'MM',
            dobyear: 'YYYY'
        }
     }
}
$scope.totaldays = 31;
$scope.totalmonths = 12;
$scope.totalyears = 100;
$scope.days = ['DD'];
for (var i = 0; i < $scope.totaldays; i += 1) {
    $scope.days.push(i + 1);
}

$scope.months = ['MM'];
for (var i = 0; i < $scope.totalmonths; i += 1) {
    $scope.months.push(i + 1);
}

$scope.years = ['YYYY'];
for (var i = 2014; i > 2014 - $scope.totalyears; i--) {
    $scope.years.push(i - 1);
}

1 个答案:

答案 0 :(得分:0)

当然,您可以将ng-repeat<option>代码结合使用ng-options

<select class="year" id="DateOfBirth_Year" name="DateOfBirthYear" required ng-pattern="\d+" ng-model="user.question5.answer.dobyear" >
    <option value="YYYY">YYYY</option>
    <option ng-repeat="o in years" value="{{o}}">{{o}}</option>
</select>

演示 Fiddle