0

I'm creating a quiz and I want to add the answer the user gives to an array (myAnswers), when the quiz is finished, I redirect my user to the summary page, where he can see the correct answer and the answer he has given. Those are both different controllers. I tried experementing with a service, but this doesn't work out...

Can someone help me with this one please?

service

var lycheeServices = angular.module('lycheeControllers', [])

lycheeServices.service('myAnswerService', function () {
var myAnswers= [];
this.AddAnswer = function(number, a){
    myAnswers[number-1] = a;
};
this.getAnswer = function(number){
    return myAnswers[number-1];
};
});

controller quiz

lycheeControllers.controller('quizCtrl', ['$scope', '$http', 'myAnswerService',
function ($scope, $http, myAnswerService) {


$scope.checked = function (answer) {
        myAnswerService.addAnswer(number, answer.answer);
    }

controller summary

lycheeControllers.controller('summaryCtrl', ['$scope', '$http', 'myAnswerService', function ($scope, $http, myAnswerService) {

$scope.myAnswer = myAnswerService.getAnswer(number);
]
Warri
  • 217
  • 1
  • 3
  • 14

1 Answers1

0

In your controller summary, when you retrieve a value using your myAnswerService.getAnswer(number);, it returns a new value and your $scope.myAnswer is a copy of the value.

If your answer is a value type, any changes on it will not affect the value in your service answer array.

If your answers array contains objects (reference type), then manipulating the properties of $scope.myAnswer will update the properties of the same object referenced by the answer inside the service's array. But if you replace it with another answer, your answer inside the answers array will not notice the change

I don't know what you're trying to achieve, but a sensible solution is you store the service object to the scope. Like this:

$scope.myAnswer = myAnswerService

Note: When you do redirects, ensure that you don't do full page refresh because your data will be cleared completely.

Khanh TO
  • 48,509
  • 13
  • 99
  • 115
  • I want to show the answer that has been given on that question (number) in my summary. So get the answer out of the array myAnswers – Warri Jan 11 '14 at 10:35
  • @Warri: please check my updated answer. BTW, what did not work out for you exactly? – Khanh TO Jan 11 '14 at 10:41
  • It works already, I just forget to add my service to my app module. Thanx for the help anyway! – Warri Jan 11 '14 at 15:46
  • @Warri: You should answer the question and accept it yourself or delete this question. Otherwise, this question will remain unanswered. – Khanh TO Jan 12 '14 at 01:42