每次有人点击答案然后执行data-ng-click =" addAnswer(questionId,0)" $ scope.answers数组被覆盖。我不确定为什么会这样做。
是因为每次将新模板加载到$ scope中都会重置吗?如果是这样,那不是我预期的行为。
感谢您的帮助。
index.html(缩写)
<div id="q" class="cta1_content ugh" data-ng-controller="testYourself">
<div ng-view></div>
</div>
测试yourself.html
<div>
<div class="row">
<h1 class="text-center">{{question.name}}</h1>
<div class="col-xs-6 col-md-3 col-md-offset-3 text-center yesno">
<a href="#/test/{{questionId+1}}" class="q" data-ng-click="addAnswer(questionId, 1)">
<span class="cta_next"><i class="icon ion-checkmark-round"></i></span>
</a>
</div>
<div class="col-xs-6 col-md-3 text-center yesno">
<a href="#/test/{{questionId+1}}" class="q" data-ng-click="addAnswer(questionId, 0)">
<span class="cta_next"><i class="icon ion-close-round"></i></span>
</a>
</div>
</div>
</div>
app.js
var calculonApp = angular.module('calculonApp', [
'ngRoute',
'calculonControllers',
'ui.bootstrap.showErrors'
]);
calculonApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/test/:questionId', {
templateUrl: 'app/partials/test-yourself.html',
controller: 'testYourself'
}).
otherwise({
redirectTo: '/test/0'
});
}]);
controller.js
calculonControllers.controller('testYourself', ['$scope', '$routeParams',
function($scope, $routeParams) {
$scope.quiz = [
{name:"a", answer: [{0: '1.', 1: '2'}], weight:25},
{name:"b", answer: [{0: '1', 1: '2'}], weight:25}
];
$scope.question = $scope.quiz[$routeParams.questionId];
$scope.questionId = parseInt($routeParams.questionId);
$scope.answers = [];
$scope.addAnswer = function(a) {
$scope.answers.push({
'question':$scope.questionId,
'answer':a
});
};
}]);
答案 0 :(得分:1)
您需要创建一个服务来跟踪答案,是的,当路线更改答案时,您的答案是否正确。
calculonApp.service('AnswerService', function() {
var answers = [];
this.addAnswers = function(questionId, a) {
answers.push({
'question':questionId,
'answer':a
});
}
return this;
});
calculonControllers.controller('testYourself', ['$scope', '$routeParams', 'AnswerService'
function($scope, $routeParams, AnswerService) {
$scope.quiz = [
{name:"a", answer: [{0: '1.', 1: '2'}], weight:25},
{name:"b", answer: [{0: '1', 1: '2'}], weight:25}
];
$scope.question = $scope.quiz[$routeParams.questionId];
$scope.questionId = parseInt($routeParams.questionId);
AnswerService.addAnswers($scope.questionId, a);
}]);