Americo Americo - 1 year ago 254
AngularJS Question

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

I have the following in my index.html

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

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

I have the following in my app.js

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

$ = {
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++) {

$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"?

Answer Source

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">

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download