Larsmanson
Larsmanson

Reputation: 413

Change selected value on button click in AngularJS

I am trying to change the value from a selectbox on a buttonclick. I have a selectbox with all the months in it, and when I click a 'previous month' button, I want to change the selected value to the previous month but what I have now does not work correctly. It only changes one time

This is my HTML:

<select name="months" ng-model="monthFromSelector" ng-change="getSelectVal('monthFromSelector')">
   <option ng-repeat="month in months" value="{{month}}">{{month}}</option>
</select>

<button ng-click="prevMonth()">Vorige maand</button>

And my controller:

$scope.months = ["Januari", "Februari", "Maart", "April", "Mei", "Juni", "Juli", "Augustus", "September", "Oktober", "November", "December"];

var now = new Date();
var thisMonth = $scope.months[now.getMonth()];

$scope.monthFromSelector = thisMonth;

$scope.prevMonth = function() {
    thisMonth = $scope.months[now.getMonth() -1]
    $scope.monthFromSelector = thisMonth;
    console.log(thisMonth)
  }

Upvotes: 0

Views: 1046

Answers (2)

afzalex
afzalex

Reputation: 8652

I think you had copy pasted this line

thisMonth = $scope.months[now.getMonth() -1]

This line is just getting current month every time.

Replacing this line with below will work fine

thisMonth = $scope.months[$scope.months.indexOf($scope.monthFromSelector) - 1]

Checkout the working example :

angular.module('myapp', [])
  .controller('myctrlr', ['$scope', function($scope) {
    $scope.message = 'message';

    $scope.months = ["Januari", "Februari", "Maart", "April", "Mei", "Juni", "Juli", "Augustus", "September", "Oktober", "November", "December"];

    var now = new Date();
    var thisMonth = $scope.months[now.getMonth()];

    $scope.monthFromSelector = thisMonth;

    $scope.prevMonth = function() {
      thisMonth = $scope.months[$scope.months.indexOf($scope.monthFromSelector) - 1]
      $scope.monthFromSelector = thisMonth;
      console.log(thisMonth)
    }
  }]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>

<div ng-app="myapp">
  <div ng-controller="myctrlr">

    <select name="months" ng-model="monthFromSelector" ng-change="getSelectVal('monthFromSelector')">
      <option ng-repeat="month in months" value="{{month}}">{{month}}</option>
    </select>

    <button ng-click="prevMonth()">Vorige maand</button>


  </div>
</div>

Upvotes: 1

Bill P
Bill P

Reputation: 3618

This is happening because you always get the previous month from the current:

thisMonth = $scope.months[now.getMonth() -1]

You need to get the previous month from the selected one:

$scope.prevMonth = function() {
    let selectedIndex = $scope.months.indexOf($scope.monthFromSelector);
    if(selectedIndex > 0) {
        $scope.monthFromSelector = $scope.months[selectedIndex - 1];
     }
}

Check the working demo: DEMO

Upvotes: 1

Related Questions