如何从angularJS中的对象数组中获取数据?

时间:2016-03-25 06:35:41

标签: javascript angularjs json

这是我的json -

{
    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来获取数据?

3 个答案:

答案 0 :(得分:2)

试试这个。在控制器中你可以使用这样的角度foreach。



<?php
$data=json_decode('{
"line1": 12,
"line2": 4,
"line3": 66,
"line4": false,
"line5": true,
"line6": [
    {
        "line7": "false",
        "line8": "true"
    },
    {
        "line9": "false",
        "line10": "false"
    }
],
"line11": 0,
"line12": 0}');
echo $data->line6[1]->line9;
exit;
?>
&#13;
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);
      })
    
    })
}]);
&#13;
&#13;
&#13;

答案 1 :(得分:0)

假设你在$scope.allAlbums中有这个json。

您可以使用

迭代所有相册的艺术家名称
$scope.allAlbums.topalbums.album.forEach(function(item) {

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

答案 2 :(得分:0)

你可以试试这个。名称将包含数组专辑名称:

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