0

I'm building a quiz using AngularJS and UI Router.

I have my app structured like this:

 - intro screen
 - app screen (where you play the actual quiz)
 - results screen (where i display the score)

The app use the same controller (MainCTRL). I store in the MainCTRL in $scope.score the score.

The problem is that when I $state.go('results'); the controller is being reseted I think and the $scope.score is equal to 0.

How can I fix this problem?

1 Answer 1

4

Controllers are not singletons, they are instantiated every time you use them in ng-controller. If you want to share state between controllers, create a service for that.

angular.module('yourModule')
    .service('ScoreService', ScoreService);

// If you want to use dependencies, you can inject them like that
ScoreService.$inject = ['dep1', 'dep2'];

function ScoreService(dep1, dep2) {
    var self = this;
    var score = 0;

    self.getScore() {
        return score;
    }
    self.setScore(value) {
        score = value;
    }

    // Other logic

    return self;
}

Inject that service into your controller and use it to get and modify score state.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.