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

匿名 (未验证) 提交于 2019-12-03 01:00:01

问题:

I'm using a REST architecture on the backend using CakePHP 3 that returns a JSON Array with this format according to firebug, it's a 200 OK, with this response:

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

My index.html file:

<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>

And my consumidor_rest.js that brings the data from the REST webservice(which is on the same server):

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

The console of firebug doesn't show any errors and the ajax call is correct with the correct response. But the ng-repeat is just showing one single dot of the ul with no value. If I use inside the ng-repeat:

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

I can see the first element displayed correctly. What's going wrong?. I guess it's a problem with how the array is being delivered by cakePHP, but I'm not sure......

回答1:

Check the data object that your are getting from the http call. I think your data object is the JSON object and the "recipes" property inside the object is your array. So consider changing your $scope.recipes = data to $scope.recipes = data.recipes.

For verifying the data object in your UI print something like this:

{{ $scope.recipes | json }}


回答2:

The problem might be that the object aren't turned into propper objects. You might wanna try to turn them into JSON objects, like so:

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

And then in the view

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


回答3:

I think your http call returns the data in another object (I suspect response.data, in your case: $scope.recipes = data.data;

Edit: just console.log your return data from the http call.



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!