I have speech recognition using switch case, and this is the code:
$scope.recog = function() {
var recognition = new SpeechRecognition();
recognition.onresult = function(event) {
$scope.filteredItems = $filter('filter')(datauser['data']['friends'], {nama : search}, false);
var result = event.results[0][0].transcript;
switch(result){
case 'login':
$scope.loginFn();
break;
case 'sign up':
$location.path('/register');
break;
case 'register':
$scope.registerFn();
break;
case 'cancel':
$scope.cancelregisterFn();
break;
//for (var i = 1; i < $scope.filteredItems.length; i++){
case 'chat with friend number ' + i:
$scope.chatWith(friend.userid , friend.nama);
break;
//}
case 'go to home':
$location.path('/home');
break;
case 'go to add friend':
$location.path('/addfriend');
break;
case 'go to friend request':
$location.path('/friendrequest');
break;
case 'go to pending request':
$location.path('/penddingrequest');
break;
case 'add':
$scope.addfriends();
break;
case 'send':
$scope.sendMessage();
break;
default:
alert(result);
alert(i);
break;
};
$scope.$apply()
};
recognition.start();
};
but, I want to use for
as loop in one case, as you can see I already made it as command, but when I delete the //
it cannot work in my application. can I use for loop inside the switch case? I use the loop is for like this:
for (var i = 1; i < $scope.filteredItems.length; i++){
case 'chat with friend number ' + i:
$scope.chatWith(friend.userid , friend.nama);
break;
}
so, in the case i use i
fron the loop. is it already detail?
EDIT
the i
that I will use in case 'chat with friend number ' + i:
is the length of index from the friend list, and all user have different amount of friends, so I cant put exact number, like 5 or 6, I must use i < $scope.filteredItems.length
for the total of friends.
Based on comment that you are trying to create dynamic switch cases inside a loop that will not work.
What you could do is remove that whole scenario from switch
something like:
if (result && result.indexOf('chat with friend number') > -1) {
// do what is needed for this case with your loop
} else {
switch (result) {
// all the other cases shown
}
}
You can try something like this:
switch(result){
case:
.
.
.
case default:
var text = "chat with friend number";
// Search if result is of type "chat with friend number" and find friend number.
var friend_no = result.indexOf(text)>-1?parseInt(result.replace(text,'')):-1
if(friend_no>-1){
// do your stuff
}
}
Note: above will evaluate all cases first. If probability of this is too high, you should try @charlietfl's approach.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.