0

我的 index.html 中有以下内容

   <header>
    <select ng-model="date.month" ng-init="currentMonth" ng-options="month for month in months">
    </select>

    <select ng-model="date.year" ng-init="date.year" ng-options="year for year in years">
    </select>
    </header>

我的 app.js 中有以下内容

.controller('MainCtrl', function ($scope) {
    var today = new Date();
    var year = today.getFullYear();
    var month = today.getMonth();

    $scope.date = {
        year: year,
        month: month
    };

    $scope.months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]

    $scope.currentMonth = $scope.months[month - 1];

    var years = [];

    var earliestYear = year - 100;
    for (var i = earliestYear; i <= year; i++) {
        years.push(i);
    }

    $scope.years = years;

    $scope.$watchCollection('date', function (date) {
        $scope.currentDate = new Date(date.year, date.month, 1);
    });

我用于“date.year”的 ng-init 有效,但不适用于“currentMonth”。但是,我知道 currentMonth 已连接到视图。为什么 ng-init 不能识别 ng-init="currentMonth"?

4

1 回答 1

2

ng-init是一个表达式,因此您需要分配currentMonth给您的date.month模型。

<select ng-model="date.month" ng-init="date.month=currentMonth" ng-options="month for month in months">
</select>

实际上并ng-init="date.year"没有做任何事情。该date.year模型已被分配2016,因此看起来可以正常工作。

plunker

于 2016-05-24T01:19:54.433 回答