Reputation: 14216
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];
}
Upvotes: 0
Views: 212
Reputation: 5825
If you don't mind the order of the array:
$scope.calenderState.push($scope.calenderState.shift());
$scope.mod2m4 = $scope.calenderState[0];
Upvotes: 1
Reputation: 5015
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>
Upvotes: 3