Angular -- ng-init 作用域变量未进入视图

Angular -- ng-init scope variable not passing into view

我的 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"?

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