V Jayanth Reddy
V Jayanth Reddy

Reputation: 101

how to access array data from api in angularjs

I want to access an array by calling API in angular js. and use them in ng-repeat

angularcode:

$scope.onsubmit = function () {
    $scope.records = [];
    var answers = [];
    // Post your data to the server here. answers contains the questionId and the users' answer.
    $http.get('http://localhost/api/leaderboard/:quizId', answers).success(function successCallbac(data,status) {
        $scope.records = data;
         //console.log(records);
    });
};

Html code:

<div ng-repeat="list in records">
    <div class="row">
        <h3>{{list}}}</h3>
        <h3> {{ list}}</h3>
    </div>
</div>  

I called an API in ng-click event ,I am receiving data from API but i cannot use them in ng-repeat records are not displaying in html instead it is showing the error:

 angular.js:12477 ReferenceError: records is not defined

how to solve this problem ??

Upvotes: 0

Views: 243

Answers (3)

Syam Pillai
Syam Pillai

Reputation: 5217

Here the record is actually a scope variable. So you can't use the variable simply as records. It should be always $scope.records

so change the code into

$scope.records = data;
    console.log($scope.records);

But if you want to use records as normal variable. You should declare it as var records

So the code will change to

var records = data;
    console.log(records);

Upvotes: 0

Aditya Singh
Aditya Singh

Reputation: 16710

Either change console.log(records); to console.log($scope.records); as mentioned in above comments as records is not defined, or comment the console.log line and it will work. It has nothing to do with ng-repeat

Upvotes: 0

PeterS
PeterS

Reputation: 2964

You have:

$scope.records = data;
console.log(records);

Obviously the second line must be:

console.log($scope.records);

As records (just "records") is not defined outside of the scope.

Upvotes: 2

Related Questions