0

I have the following in my 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>

I have the following in my 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);
    });

My ng-init for "date.year" works, but not for "currentMonth". However, I know currentMonth is connected to the view. Why isn't ng-init recognizing ng-init="currentMonth"?

1 Answer 1

2

ng-init is an expression so you need to assign currentMonth to your date.month model.

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

The ng-init="date.year" doesn't actually do anything. The date.year model has already been assigned 2016 so it looks like it works.

See plunker

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.