Angular - ng-init范围变量未传入视图

时间:2016-05-24 00:34:09

标签: angularjs angularjs-ng-init ng-init

我的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);
    });

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

1 个答案:

答案 0 :(得分: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

相关问题