ng-repeat 未显示 AngularJS 1.5 中的 JSON 数组列表,但我可以单独查看值

ng-repeat not showing list of JSON array in AngularJS 1.5, but I can see values individually

我在使用 CakePHP 3 的后端使用 REST 架构,根据 firebug,returns 一个具有这种格式的 JSON 数组,它是 200 OK,有这个响应:

    {
    "recipes": [
        {
            "id": 0,
            "name": "modificadodsadasdas"
        },
        {
            "id": 1,
            "name": "dasdasdasdasdas"
        }
    ]
}

我的 index.html 文件:

<html>
<head>

</head>
<body ng-app="AppRecetas">
  <div ng-controller="RecetasCtrl">
    <ul ng-repeat="recipe in recipes">
      <li>{{recipe.name}}</li>
    </ul>
</div>
<script src="js/angular.min.js"></script>
<script src="js/consumidor_rest.js"></script>
</body>
</html>

我的 consumidor_rest.js 从 REST 网络服务(位于同一台服务器上)获取数据:

var app = angular.module("AppRecetas", []);

app.controller("RecetasCtrl", function($scope, $http) {
  $http.get('http://localhost/services/recipes/index.json').
    success(function(data, status, headers, config) {
      $scope.recipes = data;
    }).
    error(function(data, status, headers, config) {
      // log error
    });
});

firebug 的控制台未显示任何错误,ajax 调用正确且响应正确。但是 ng-repeat 只是显示 ul 的一个点,没有任何价值。如果我在 ng-repeat 中使用:

 <li>{{recipe[0].name}}</li>

我可以看到第一个元素正确显示。怎么了?我猜这是 cakePHP 如何传递数组的问题,但我不确定......

我认为你的 http 调用 return 是另一个对象中的数据(我怀疑 response.data,在你的情况下:$scope.recipes = data.data;

编辑:只是 console.log 来自 http 调用的 return 数据。

检查您从 http 调用中获取的数据对象。我认为您的数据对象是 JSON 对象,对象内部的 "recipes" 属性 是您的数组。因此,请考虑将 $scope.recipes = 数据更改为 $scope.recipes = data.recipes

为了验证 UI 中的数据对象,请打印如下内容:

{{ $scope.recipes | json }}

问题可能是对象没有变成合适的对象。 您可能想尝试将它们变成 JSON 对象,如下所示:

for(var i = 0; i < recipes.length; i++){
   recipesArray.push(JSON.parse(recipes[i]));
}
$scope.recipes = recipesArray;

然后在视图中

<ul ng-repeat="recipe in recipes">
  <li>{{recipe.name}}</li>
</ul>