Alexey  Koptyaev
Alexey Koptyaev

Reputation: 317

Using $http.get in ng-repeat causes multiple errors

I have a function what returns an array of items by group Id. Here it is:

var getChoices = function (groupId) {
    var request = $http.get(_baseUrl + 'choice', { params: { choiceGroupId: groupId } });

    return request.then(function(result) {
        if (resources.ok(result)) {
            return result.data.items;
        }
    }, function(error) {

    });
}

It works fine when I bind it to button, but when I try to make ng-repeat over this function results I have multiple errors in browser console.

<md-list>
    <md-list-item ng-repeat="choice in getChoices(choiceGroupId)">
        {{choice}}
    </md-list-item>
</md-list>

I've also tries this, but result is the same.

<md-list ng-init="choices = {{getChoices(choiceGroupId)}}">
    <md-list-item ng-repeat="choice in choices">
        {{choice}}
    </md-list-item>
</md-list>

I've seen answers to questions like this, but there people suggested to make request in the controller, then fill the array with data, and iterate over array values, but this doesn't suit my case because I need that choiceGroupId from the UI side.

It seems like browser tries to evaluate get request on each tick and something like overflow happens. How can I handle this to call 'get' once and then iterate over returned result?

Upvotes: 0

Views: 53

Answers (1)

Jekin Kalariya
Jekin Kalariya

Reputation: 3507

Check If your choices variable has duplication of value , If yes than try below code

<md-list>
    <md-list-item ng-repeat="choice in choices track by $index">
        {{choice}}
    </md-list-item>
</md-list>



var getChoices = function (groupId) {
    var request = $http.get(_baseUrl + 'choice', { params: { choiceGroupId: groupId } });

    return request.then(function(result) {
        if (resources.ok(result)) {
            $scope.choices= result.data.items;
        }
    }, function(error) {

    });
}

Upvotes: 2

Related Questions