如何用AngularJS处理一个数组

How to process an array with AngularJS?

本文关键字:一个 数组 何用 AngularJS 处理      更新时间:2023-09-26

我有一个API返回以下简单的JSON数组:

[
  "efd98ad-first_key",
  "100eb0a-second_key"
]

我试图用Angular渲染这个表:

<div name="listkeys" class="container">
  <div class="starter-template">
    <div ng-bind-html="message"></div>
    <table class="table table-striped table-bordered table-condensed sortable" ng-init="getKeys()">
      <tr>
        <th>bucket</th>
      </tr>
      <tr ng-repeat="bucket in buckets">
        <td>{{bucket}}</td>
      </tr>
    </table>
  </div>
</div>

JS:

var app = angular.module('flipDaSwitch', ['ngSanitize']);
app.controller('ListKeys', function($scope, $http) {
  $scope.getKeys = function() {
    $http.get('/api/keys').
      success(function (data) {
        $scope.response = data;
      }).
      error(function (data){
        $scope.response = {}
      });
  };
});

它除了抛出"Uncaught object"错误之外什么也不做,就是这样。

我如何调试它失败的原因?

您将值存储在$scope.response中,但您在ng-repeat中使用$scope.bucket:

$scope.getKeys = function() {
$http.get('/api/keys').
  success(function (data) {
    $scope.buckets= data;
  }).
  error(function (data){
    $scope.buckets= {}
  });

};

看起来您没有一个名为buckets的范围项。我希望看到:

$scope.buckets = data