javascript loop through messages
angularjs, javascript, loops
Solution
Use an array instead, and it's a bit easier, you'd just increment a number on each click, and use that number to select the item from the array
var msg = [
"hello1",
"hello2",
"hello3"
];
var i = 0;
var $scope = {};
$scope.clickMsg = function () {
console.log( msg[i] );
i++; // increment
if (i === msg.length) i = 0; // reset when end is reached
}
document.getElementById('test').addEventListener('click', $scope.clickMsg)
<button id="test">Click</button>
Problem
I have 3 messages in variables. ``` var msg1 = "hello1"; var msg2 = "hello2"; var msg3 = "hello3"; ``` I am trying to create a function that when i click it the first time it console.log(msg1), when i click it the second time it console.log(msg2), 3rd time console.log(msg3), 4th time console.log(msg1) and 5th msg2 etc. ``` $scope.clickMsg = function () { console.log(msg1); } ``` i've tried loops, timers etc but i could not make it work. Does anyone know how to do this?