如何从angularjs中的api访问数组数据

时间:2016-04-25 10:30:03

标签: javascript angularjs angularjs-scope angularjs-ng-repeat

我想通过在角度js中调用API来访问数组。并在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代码:

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

我在ng-click事件中调用了一个API,我从API接收数据但我不能在ng-repeat记录中使用它们不会在html中显示而是显示错误:

 angular.js:12477 ReferenceError: records is not defined

如何解决这个问题?

3 个答案:

答案 0 :(得分:2)

你有:

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

显然第二行必须是:

console.log($scope.records);

由于记录(仅“记录”)未在范围之外定义。

答案 1 :(得分:0)

如上面的评论所述,将console.log(records);更改为console.log($scope.records);,因为records未定义,或评论console.log行,它会起作用。它与ng-repeat

无关

答案 2 :(得分:0)

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

所以将代码更改为

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

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

因此代码将更改为

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