我刚刚进入angularJS和我的第一个项目我试图建立一个测验创建者。我希望人们能够创建结果,问题,答案以及结果答案的加权映射。我的HTML看起来像这样:
<div ng-controller="QuizCtrl">
<div class="result" ng-repeat="result in quiz.results">
<input ng-model="result.title" /> [<a href ng-click="quiz.results.splice($index, 1)">X</a>]<br />
</div>
<div class="question row" ng-repeat="question in quiz.questions">
<div class="col-sm-4 col-md-4 col-lg-4">
<input ng-model="question.title" /> [<a href ng-click="quiz.questions.splice($index, 1)">X</a>]<br />
<a href ng-click="addAnswer($index)">add answer</a>
</div>
<div class="col-sm-8 col-md-8 col-lg-8">
<div class="answer" ng-repeat="answer in question.answers">
<input ng-model="answer.title" /> [<a href ng-click="question.answers.splice($index, 1)">X</a>]<br />
<div class="answerresult" ng-repeat="answerresult in answer.answerresults">
{{ quiz.results[$index].title }}:
<select ng-change="answerresult.result = $index" ng-model="answerresult.weight" ng-options="i for i in [1,2,3]"></select>
</div>
</div>
</div>
</div>
</div>
基础数据结构如下:
angular.module('testApp')
.controller('QuizCtrl', function ($scope) {
$scope.quiz = {
questions: [
{title: 'question 1', answers: [
{title: 'answer 1', answerresults:[
{'result': 0, weight: 2},
{'result': 1, weight: 3}
]},
{title: 'answer 3', answerresults:[
{'result': 0, weight: 2},
{'result': 1, weight: 2}
]}
]},
{title: 'question 2', answers: [
{title: 'answer 1', answerresults:[
{'result': 0, weight: 1},
{'result': 1, weight: 2}
]},
{title: 'answer 2', answerresults:[
{'result': 0, weight: 2},
{'result': 1, weight: 2}
]},
{title: 'answer 3', answerresults:[
{'result': 0, weight: 1},
{'result': 1, weight: 3}
]}
]}
],
results: [
{title: 'result 1'},
{title: 'result 2'}
],
};
});
现在我的问题:
提前感谢您的回答,对不起,如果这是一个愚蠢的问题。我昨天只是潜入角落..
答案 0 :(得分:0)
好的,我现在用嵌套的for循环解决了。我不知道这是否是正确的角度方式,但它有效:
$scope.addResult = function() {
$scope.quiz.results.push({});
for(var question in $scope.quiz.questions ) {
for(var answer in $scope.quiz.questions[question].answers) {
$scope.quiz.questions[question].answers[answer].answerresults.push({});
}
}
};
$scope.removeResult = function(index) {
$scope.quiz.results.splice(index, 1);
for(var question in $scope.quiz.questions ) {
for(var answer in $scope.quiz.questions[question].answers) {
$scope.quiz.questions[question].answers[answer].answerresults.splice(index, 1);
}
}
};