我想在 AngualrJS 中创建一个表单生成器,能够添加和删除无限的子问题来选择父问题,如下所示:
Question 1
---Choice1.1
---Choice1.2
---Child-Question 1.1
---Choice1
---Choice2
---Child-Question 1.1.2
---Choice1
---Choice2
---Choice3
---Choice1.3
Question 2
---Choice2.1
---Choice2.2
---Choice2.3
这是我想要动态创建的示例 JSON:
{
title: "string",
description: "string",
questionType: 0,
option: {
min: 0,
max: 0,
step: 0,
unit: "string"
},
choices: [
{
title: "string",
order: 0,
matrixPosition: 0,
childQuestionTemplate: {}
},
{
title: "string",
order: 0,
matrixPosition: 0,
childQuestionTemplate: {
title: "string",
description: "string",
questionType: 0,
option: {},
choices: [
{
title: "string",
order: 0,
matrixPosition: 0,
childQuestionTemplate: {}
}
]
}
},
{
title: "string",
order: 0,
matrixPosition: 0,
childQuestionTemplate: {
id: 0,
title: "string",
description: "string",
questionType: 0,
option: {
min: 0,
max: 0,
step: 0,
unit: "string"
},
choices: [
{
title: "string",
order: 0,
matrixPosition: 0,
childQuestionTemplate: {
title: "string",
description: "string",
questionType: 0,
option: {},
choices: [
{
title: "string",
order: 0,
matrixPosition: 0,
childQuestionTemplate: {}
}
]
}
}
]
}
},
{
title: "string",
order: 0,
matrixPosition: 0,
childQuestionTemplate: {}
}
]
}
现在我想知道如何从 HTML 中选择一个选项(获取路径),将一个子问题推送到其他子问题的选择中?
最佳答案
如果你想从html中获取选择的路径,你可以通过为你的问题提供一个索引(唯一ID)来做到这一点,我建议你将“选择”从数组更改为对象,这样你就可以直接访问它使用指定的唯一 ID。
示例是:
var jsonObject = {
"1-1" : {
title: "primary index",
description: "string",
questionType: 0,
option: {
min: 0,
max: 0,
step: 0,
unit: "string"
},
choices: {
"2-1" : {
title: "secondary index",
order: 0,
matrixPosition: 0,
childQuestionTemplate: {}
},
"2-2" : {
title: "string",
order: 0,
matrixPosition: 0,
childQuestionTemplate: {
title: "string",
description: "string",
questionType: 0,
option: {},
choices: {
"3-1" : {
title: "tertiary index 1",
order: 0,
matrixPosition: 0,
childQuestionTemplate: {}
},
"3-2" : {
title: "tertiary index 2",
order: 0,
matrixPosition: 0,
childQuestionTemplate: {}
}
}
}
}
}
}
}
所以如果你想删除一个选择,你可以这样做
var primaryIndex = "1-1";
//remove on the tertiary index
var secondaryIndex = "2-2";
var tertiaryIndexToDelete = "3-1";
delete jsonObject[primaryIndex].choices[secondaryIndex].childQuestionTemplate.choices[tertiaryIndexToDelete];
//remove on the secondary index
var secondaryIndexToDelete = "2-2";
delete jsonObject[primaryIndex].choices[secondaryIndexToDelete];
现在,如果您想为问题添加选项,您可以这样做
var newChoice = {
title: "new choice",
order: 0,
matrixPosition: 0,
childQuestionTemplate: {}
}
var indexOfNewChoice = "2-3";
jsonObject["1-1"].choices[indexOfNewChoice] = newChoice;
我希望这会有所帮助。
关于javascript - 在 AngularJS 中添加和删除数组中的嵌套项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41219345/