如何在 AngularJS 中从 API 访问数组数据

how to access array data from api in angularjs

本文关键字:访问 数组 数据 API 中从 AngularJS      更新时间:2023-09-26

我想通过在角度js中调用API来访问数组,并在ng-repeat中使用它们

角度码:

$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);
    });
};

网页代码:

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

我在 ng-click 事件中调用了一个 API,我正在从 API 接收数据,但我无法在 ng 中使用它们,重复记录没有以 html 显示,而是显示错误:

 angular.js:12477 ReferenceError: records is not defined

如何解决这个问题??

你有:

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

显然,第二行必须是:

console.log($scope.records);

由于记录(只是"记录")不是在范围之外定义的。

要么将console.log(records);更改为上述注释中提到的console.log($scope.records);,因为未定义records,要么注释console.log行,它将起作用。它与ng-repeat无关

这里的记录实际上是一个范围变量。因此,您不能简单地将变量用作records。它应该始终$scope.records

所以将代码更改为

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

但是如果你想使用records作为正态变量。您应该将其声明为var records

所以代码将更改为

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