[英]how to use for loop inside the switch case in angularjs?
我使用 switch case 进行语音识别,这是代码:
$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();
};
但是,我想在一种情况下使用for
as 循环,正如您所看到的,我已经将其作为命令,但是当我删除//
它无法在我的应用程序中工作。 我可以在开关盒内使用 for 循环吗? 我使用的循环是这样的:
for (var i = 1; i < $scope.filteredItems.length; i++){
case 'chat with friend number ' + i:
$scope.chatWith(friend.userid , friend.nama);
break;
}
所以,如果我在循环中使用i
。 已经很详细了吗?
编辑
在i
,我会在情况下使用'chat with friend number ' + i:
是指数从朋友列表的长度,以及所有用户都有不同数额的朋友,所以我不能把确切的数字,如5或6,我必须使用i < $scope.filteredItems.length
作为朋友总数。
根据您尝试在无法工作的循环内创建动态切换案例的评论。
您可以做的是从switch
删除整个场景,例如:
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
}
}
你可以尝试这样的事情:
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
}
}
注意:以上将首先评估所有情况。 如果这种可能性太高,您应该尝试@charlietfl 的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.