2016-03-25 40 views
0

这里是我的json-如何从angularJS中的对象数组中获取数据?

{ 
    topalbums: { 
     album: [ 
     { 
      name: "The Very Best of Cher", 
      playcount: 1634402, 
      mbid: "a7e2dad7-e733-4bee-9db1-b31e3183eaf5", 
      url: "http://www.last.fm/music/Cher/The+Very+Best+of+Cher", 
      artist: { 
      name: "Cher", 
      mbid: "bfcc6d75-a6a5-4bc6-8282-47aec8531818", 
      url: "http://www.last.fm/music/Cher" 
      } 
     } 
     ] 
    } 
} 

如何获取数据,通过循环,采用了棱角分明的控制,每即将到来的对象artist.name?

+1

是的,你需要遍历对象为'album'是对象 – Satpal

+0

在控制器的阵列,如何循环? –

+0

$ scope.data = topTracksService.list; $ scope.tracks = $ scope.data.track; console.log($ scope.tracks); angular.forEach($ scope.tracks,function(value,key){});以上代码不起作用 –

回答

2

试试这个控制器,你可以像这样使用angular foreach。

var app = angular.module("app",[]) 
 
app.controller('ctrl',['$scope', function($scope){ 
 
     $scope.data={ 
 
     topalbums: { 
 
      album: [ 
 
      { 
 
      name: "The Very Best of Cher", 
 
      playcount: 1634402, 
 
      mbid: "a7e2dad7-e733-4bee-9db1-b31e3183eaf5", 
 
      url: "http://www.last.fm/music/Cher/The+Very+Best+of+Cher", 
 
      artist: { 
 
       name: "Cher", 
 
       mbid: "bfcc6d75-a6a5-4bc6-8282-47aec8531818", 
 
       url: "http://www.last.fm/music/Cher" 
 
       } 
 
      }, 
 
      { 
 
      name: "The Very Best of Cher", 
 
      playcount: 1634402, 
 
      mbid: "a7e2dad7-e733-4bee-9db1-b31e3183eaf5", 
 
      url: "http://www.last.fm/music/Cher/The+Very+Best+of+Cher", 
 
      artist: { 
 
       name: "Cher2", 
 
       mbid: "bfcc6d75-a6a5-4bc6-8282-47aec8531818", 
 
       url: "http://www.last.fm/music/Cher" 
 
       } 
 
      } 
 
      ] 
 
     } 
 
     }; 
 
    
 
    
 
    angular.forEach($scope.data.topalbums,function(album){ 
 
    angular.forEach(album,function(a){ 
 
     alert(a.artist.name); 
 
     console.log(a.artist.name); 
 
     }) 
 
    
 
    }) 
 
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script> 
 
<div ng-app="app" ng-controller="ctrl"> 
 
<div class="item item-checkbox"> 
 
    <div ng-repeat="album in data.topalbums"> 
 
     <p ng-repeat="a in album">{{a.artist.name}}</p> 
 
</div>  
 
</div>

+0

我想在控制器部分找到artist.name,而不是查看。在我的问题中,artist.name被传递给我的控制器中的一个函数。 –

+0

我更新了我的答案。 –

+0

这不起作用。没有任何显示 –

0

比方说,你有这样的JSON在$scope.allAlbums

可以使用

$scope.allAlbums.topalbums.album.forEach(function(item) { 

    console.log(item.artist.name) 
}) 
+0

得到错误 - angular.min.js:111 TypeError:无法读取未定义的属性“专辑” –

+0

是否可以在控制台中打印$ scope.allAlbums.topalbums? –

+0

您的错误表示'$ scope.allAlbums'中没有'topalbums'。检查到这个级别,并确保你的'$ scope.allAlbums'包含给定的json。 –

0

遍历所有专辑的艺术家名字你可以试试这个。名称将包含数组专辑名称:

var names = data.topalbums.album.map(function(item){ 
       return item.artist.name; 
}); 
相关问题