我尝试将下拉菜单设置为当月,即10月,但它不起作用,任何线索的人?
http://plnkr.co/edit/qtPvCy4phNQW6I6IPQyr?p=preview
app.controller('MainCtrl', function($scope) {
var d = new Date();
var month = new Array();
var this_year = d.getFullYear();
month[0] = "January " + this_year;
month[1] = "February " + this_year;
month[2] = "March " + this_year;
month[3] = "April " + this_year;
month[4] = "May " + this_year;
month[5] = "June " + this_year;
month[6] = "July " + this_year;
month[7] = "August " + this_year;
month[8] = "September " + this_year;
month[9] = "October " + this_year;
month[10] = "November " + this_year;
month[11] = "December " + this_year;
$scope.months = month;
$scope.this_month = month[d.getMonth()] + " " + this_year; // won't work?
});
答案 0 :(得分:1)
您可以通过将当前月份分配到model
selected_month来设置默认月份。
$scope.selected_month = $scope.months[d.getMonth()];
答案 1 :(得分:0)
问题解决了:ngInit用于设置默认值,并且您尝试设置但错误的方式,请参阅此示例
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
var d = new Date();
var month = new Array();
var this_year = d.getFullYear();
month[0] = "January " + this_year;
month[1] = "February " + this_year;
month[2] = "March " + this_year;
month[3] = "April " + this_year;
month[4] = "May " + this_year;
month[5] = "June " + this_year;
month[6] = "July " + this_year;
month[7] = "August " + this_year;
month[8] = "September " + this_year;
month[9] = "October " + this_year;
month[10] = "November " + this_year;
month[11] = "December " + this_year;
$scope.months = month;
$scope.this_month = month[d.getMonth()]; // won't work?
});
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js@1.0.x" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js" data-semver="1.0.7"></script>
</head>
<body ng-controller="MainCtrl">
<select style="position: relative;margin-top: -50px;" class="pull-right" ng-model="selected_month" ng-options="m for m in months" ng-init="selected_month = this_month">
</select>
</body>
</html>
答案 2 :(得分:0)
您最常在控制器上定义一个函数,在ng-init上调用方法。 例如
ng-init="this_month()"
在控制器上更改此行:
$scope.this_month = month[d.getMonth()] + " " + this_year; // won't work?
为:
$scope.this_month = //Change this line....
function(){
$scope.selected_month = $scope.months[d.getMonth()];
};