【问题标题】:ng-repeat not showing list of JSON array in AngularJS 1.5, but I can see values individuallyng-repeat 未在 AngularJS 1.5 中显示 JSON 数组列表,但我可以单独查看值
【发布时间】:2016-08-14 17:41:07
【问题描述】:

我正在使用 CakePHP 3 在后端使用 REST 架构,它根据 firebug 返回具有这种格式的 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 传递数组的方式有问题,但我不确定......

【问题讨论】:

  • 尝试将$scope.recipes 设置为data.recipes
  • 需要看到你的回应..

标签: arrays angularjs json ng-repeat


【解决方案1】:

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

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

{{ $scope.recipes | json }}

【讨论】:

    【解决方案2】:

    问题可能是对象没有变成合适的对象。 您可能想尝试将它们转换为 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>
    

    【讨论】:

      【解决方案3】:

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

      编辑:只需 console.log 您从 http 调用返回的数据。

      【讨论】:

        猜你喜欢
        • 2017-07-21
        • 2018-01-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多