pass data between controllers (service) angular

123 views Asked by At

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);
]
1

There are 1 answers

4
Khanh TO On

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.