我有一个angular app,其界面类似于"命令行",用户可以输入命令来浏览网站。当用户键入"注册"时,我想询问用户一系列问题(例如,他们的姓名,电子邮件等),并且对于每个问题,他们在命令行中输入提交数据。看起来很简单,但我无法找出执行此操作的最佳方法(哈哈,得到它?执行?好吧......)
无论如何,这里有一些伪代码解释了我需要发生的事情:
HTML:
<div id="cli">
<p ng-repeat="message in output">{{message}}</p>
<form ng-submit="execute()">
<input type="text" ng-model="input">
</form>
</div>
JS:
app.controller(&#34; CommandCtrl&#34;,function($ scope){
var output = {},
prompts = [
{
message: "What's your name?",
responseType: "string",
value: "name"
},
{
message: "What's your email?",
responseType: "email",
value: "email"
},
{
message: "Are you sure you want to continue? (y/n)",
responseType: "y/n",
value: null
}
],
programs = {
signUp: function() {
// What is the correct way to loop through these prompts,
// only showing one at a time and waiting for a response?
forEach(prompts, function(promptData) {
prompt(promptData.message)
.then(function(input) {
if (validate(input, promptData.value)) {
output[promptData.message] = input;
goToNextArrayItem();
} else {
// The input was invalid, tell the user and ask for the data again
tryItAgain();
}
});
});
}
}
$scope.execute = function() {
var input = $scope.input;
if (input == 'sign-up') {
programs.signUp();
}
$scope.$broadcast("recievedInput", input);
}
function prompt(message) {
return $q(function(resolve, reject) {
writeLine(message);
$scope.$on("recievedInput", function(input) {
resolve(message);
});
});
}
function writeLine(message) {
$scope.output.push(message);
}
function validate(input, dataType) {
switch (dataType) {
case: 'string':
return typeof input == 'string';
break;
case 'email':
// Hypothetical email validation function
return validateEmail(dataType);
break;
....
default:
.....
}
}
});
基本上我需要遍历提示,为每个提示运行prompt()函数(当用户输入内容时应该返回一个promise)。我需要能够从用户那里获取每个提示的输入并将其保存在输出对象中,并且能够继续&#34;继续&#34;到下一个提示或&#34;返回&#34;到前一个。有没有什么好方法可以在角度中循环承诺?