我正在尝试使用 angular.js、hammer.js 和 topcoat 制作移动网络应用程序。
我在显示 Json 文件中的数据时遇到一些问题,如下所示:
{
"version": "1",
"artists": {
"artist1": {
"name": "artist1name",
"jpeg": "../img/artist/artist1.jpg",
"albums": {
"album1": {
"type": "cd",
"title": "titlealbum1",
"subtitle": "subtitlealbum1",
"jpeg": "../img/album1.jpg",
"price": "12.00",
"anystring1": "anystring1album1",
"anystring2": "anystring2album1"
},
"album2": [{
"type": "cd",
"title": "titlealbum2",
"subtitle": "subtitlealbum2",
"jpeg": "../img/album2.jpg",
"price": "12.00",
"anystring1": "anystring1album2",
"anystring2": "anystring2album2"
}],
"album3": [{
"type": "cd",
"title": "titlealbum3",
"subtitle": "subtitlealbum3",
"jpeg": "../img/album3.jpg",
"price": "13.00",
"anystring1": "anystring1album3",
"anystring2": "anystring2album3"
}]
}
},
"artist2": {
"name": "artist2name",
"jpeg": "../img/artist/artist2.jpg",
我的js文件是这样的:
angular.module('list', [])
function ListCtrl ($scope, $http) {
$http({method: 'GET', url: 'json/json_price_1.json'}).success(function(data)
{
$scope.artists = data.artists; // response data
$scope.albums = data.artists.albums; /this is where im getting trouble
});
};
我的 HTML 文件是这样的:
<body ng-app="list">
<h3>Titulos</h3>
<div ng-controller="ListCtrl">
<ul ng-repeat="artist in artists">
<li >{{artist.name}}</li>
</ul>
</div>
<div ng-controller="ListCtrl">
<ul ng-repeat="album in albums">
<li >{{album.title}}</li> //not working here.
</ul>
</div>
我想显示所有专辑,如果我的用户选择特定艺术家,我想过滤这些专辑。 这里的问题是我将如何选择这个嵌套的 json。顺便说一句,艺术家名称显示正确。
第二个问题是,我将如何使用文本字段过滤这些艺术家。
最佳答案
我建议这样:
$http({method: 'GET', url: 'json/json_price_1.json'}).success(function(data) {
$scope.artists = [];
angular.forEach(data.artists, function(value, key) {
$scope.artists.push(value);
});
$scope.isVisible = function(name){
return true;// return false to hide this artist's albums
};
});
然后:
<div ng-controller="ListCtrl">
<ul>
<li ng-repeat="artist in artists">{{artist.name}}</li>
</ul>
<ul ng-repeat="artist in artists" ng-show="isVisible(artist.name)">
<li ng-repeat="album in artist.albums">{{album.title}}</li>
</ul>
</div>
关于javascript - 使用 AngularJS 访问嵌套 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19824959/