0

I am creating a quiz in angular and i use this code:

<ul>
    <li ng-repeat="choice in choices" class="choices" ng-click="setSelection(choice)">{{choice}}</li>
</ul>

var choiceSelection = {
        isSelected: false,
        userAnswers: [],
        setSelection: function(choice) {
            this.userAnswers.push(choice);
            console.log(this.userAnswers);
        }
    };


$scope.setSelection = choiceSelection.setSelection;

I want to store the users choice in the userAnswers array, but the this in setSelection is undefined and therefore this.userAnswers nor this.isSelected works. This code works in normal JS, I just tested it. What's going on here?

1 Answer 1

1

You could bind the proper value for this to your setSelection function:

var choiceSelection = new function ( ) {
    this.isSelected = false;
    this.userAnswers = [];

    this.setSelection = function(choice) {
        this.userAnswers.push(choice);
        console.log(this.userAnswers);
    }.bind( this );
} ;

$scope.setSelection = choiceSelection.setSelection;
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.