idontknow
idontknow

Reputation: 1106

Angularjs "this" is undefined in normal object

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?

Upvotes: 0

Views: 2231

Answers (1)

Paul
Paul

Reputation: 141877

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;

Upvotes: 1

Related Questions