0

I have a variable that is set to an array index, and I want to try and loop through it on click. I have it initially set like:

 $scope.calenderState = ["day","week","month","year"];
 $scope.mod2m4 = $scope.calenderState[0];

and a click function connected that sends mod2m4 like:

 ng-click ="changeCal(mod2m4)" 

So right now it would send "day". Every time I click it, I want it to increment to the next item, (so week) unless its year, then back to day. How do I handle this scenario?

Edit: I am able to solve it like so, but I'm wondering if there is a bit more of an elegant solution?

var ind = _.indexOf($scope.calenderState, current);
if(ind == 3){
    $scope.mod2m4 = $scope.calenderState[0];
}else{
    $scope.mod2m4 = $scope.calenderState[ind + 1];
}

2 Answers 2

3

Maybe try storing just the index as a scope variable, then abstract the increment operation into a function (to deal with wrapping around)

$scope.index = 0
$scope.increment = function() {
  $scope.index += 1;
  if ($scope.index > 3) {
    $scope.index = 0;
  }
}

Then in your view if you want to display the value you can use the following expression:

<p>{{calendarState[index]}}</p>
Sign up to request clarification or add additional context in comments.

Comments

1

If you don't mind the order of the array:

$scope.calenderState.push($scope.calenderState.shift());
$scope.mod2m4 = $scope.calenderState[0];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.