Max Gabderakhmanov
Max Gabderakhmanov

Reputation: 922

Current year (by default) for the selector in view (AngularJS)

I'm new to the AngularJS. Here is my $scope of years for the selector in html:

//get it from the backend 
$scope.years = ['2014', '2015', '2016', '2017', '2018'];

here is my html where I use this $scope:

<select name="repeatSelect" id="repeatSelect" ng-model="yearFromSelector">
    <option ng-repeat="year in years" value="{{year}}">{{year}}</option>
</select>

when I run my app, I see an empty selector (with years inside) by default:

enter image description here

but I need to default selector shows the current year (with the other years inside). Please advise how I can do that?

Upvotes: 0

Views: 1370

Answers (5)

Ram_T
Ram_T

Reputation: 8484

Do this

<select ng-init="yearFromSelector='2017'" name="repeatSelect" id="repeatSelect" ng-model="yearFromSelector">
    <option ng-repeat="year in years" value="{{year}}">{{year}}</option>
</select>

Upvotes: 1

nivas
nivas

Reputation: 3186

Here is the simple way to implement using angularjs. You don't need to use value="{{year}}" because you are already defining the actual value using ng-model

var myApp = angular.module('myApp',[]);

function MyCtrl($scope) {
    $scope.thisYear = new Date().getFullYear();
    $scope.years = ['2014', '2015', '2016', '2017', '2018'];
}
<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>

Upvotes: 0

Sai
Sai

Reputation: 2668

Simplified answer:

JS:

$scope.yearFromSelector = new Date().getFullYear().toString();

HTML:

 <select ng-model="yearFromSelector" ng-options="year as year for year in years">
  </select>

Upvotes: 0

Shaishab Roy
Shaishab Roy

Reputation: 16805

you can use this code.

In controller:

$scope.years = ['2014', '2015', '2016', '2017', '2018'];
var currentYear = new Date().getFullYear();
var index = $scope.years.indexOf(currentYear.toString());

$scope.yearFromSelector = $scope.years[index];

and HTML:

<select name="repeatSelect" id="repeatSelect" ng-model="yearFromSelector">
    <option ng-repeat="year in years" value="{{year}}">{{year}}</option>
</select>

or

<select name="repeatSelect" id="repeatSelect" ng-model="yearFromSelector" ng-options="year as year for year in years">
    </select>

Upvotes: 1

Krunal Modi
Krunal Modi

Reputation: 747

Add this to Controller:

$scope.currentYear = new Date().getFullYear();

Add this to View:

<select name="repeatSelect" id="repeatSelect" ng-model="yearFromSelector">
    <option ng-selected="year == currentYear" ng-repeat="year in years" value="{{year}}">{{year}}</option>
</select>

Upvotes: 0

Related Questions