我是AngularJS的新手。这是html中选择器的$scope
年:
//get it from the backend
$scope.years = ['2014', '2015', '2016', '2017', '2018'];
这是我的html,我使用这个$scope
:
<select name="repeatSelect" id="repeatSelect" ng-model="yearFromSelector">
<option ng-repeat="year in years" value="{{year}}">{{year}}</option>
</select>
当我运行我的应用程序时,默认情况下我看到一个空的选择器(里面有几年):
但我需要默认选择器显示当前年份(其他年份内)。请告诉我该怎么做?
答案 0 :(得分:1)
这样做
<select ng-init="yearFromSelector='2017'" name="repeatSelect" id="repeatSelect" ng-model="yearFromSelector">
<option ng-repeat="year in years" value="{{year}}">{{year}}</option>
</select>
答案 1 :(得分:1)
您可以使用此代码。
在控制器中:
$scope.years = ['2014', '2015', '2016', '2017', '2018'];
var currentYear = new Date().getFullYear();
var index = $scope.years.indexOf(currentYear.toString());
$scope.yearFromSelector = $scope.years[index];
和HTML:
<select name="repeatSelect" id="repeatSelect" ng-model="yearFromSelector">
<option ng-repeat="year in years" value="{{year}}">{{year}}</option>
</select>
或
<select name="repeatSelect" id="repeatSelect" ng-model="yearFromSelector" ng-options="year as year for year in years">
</select>
答案 2 :(得分:0)
将此添加到Controller:
$scope.currentYear = new Date().getFullYear();
将此添加到视图:
<select name="repeatSelect" id="repeatSelect" ng-model="yearFromSelector">
<option ng-selected="year == currentYear" ng-repeat="year in years" value="{{year}}">{{year}}</option>
</select>
答案 3 :(得分:0)
简化回答:
JS:
$scope.yearFromSelector = new Date().getFullYear().toString();
HTML:
<select ng-model="yearFromSelector" ng-options="year as year for year in years">
</select>
答案 4 :(得分:0)
这是使用angularjs实现的简单方法。您不需要使用value =&#34; {{year}}&#34;因为您已经使用ng-model
定义了实际值
var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
$scope.thisYear = new Date().getFullYear();
$scope.years = ['2014', '2015', '2016', '2017', '2018'];
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
<select name="repeatSelect" id="repeatSelect" ng-model="thisYear">
<option ng-repeat="year in years">{{year}}</option>
</select>
</div>
&#13;