视图中的选择器的当前年份(默认情况下)(AngularJS)

时间:2017-01-06 11:50:56

标签: javascript angularjs

我是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>

当我运行我的应用程序时,默认情况下我看到一个空的选择器(里面有几年):

enter image description here

但我需要默认选择器显示当前年份(其他年份内)。请告诉我该怎么做?

5 个答案:

答案 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

定义了实际值

&#13;
&#13;
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;
&#13;
&#13;