我正在尝试使用AngularJS解析嵌套的JSON。其中的项目将在整个页面中使用,但是其中也嵌套了新闻项目。我不确定如何解决这个问题。
test.json
{
"CustomerName" : "TEST",
"PaidCustomer" : true,
"LaunchEndDate" : "24-07-2021",
"LauncherTitle" : "Launcher Title",
"LauncherSlogan" : "LauncherSlogan",
"CommunityLogo" : "logo.jpg",
"news" : [
{
"Title" : "News 1",
"Description" : "Newsmessage 1",
"FeaturesImage" : "",
"Author" : "Hutserino",
"Tags" : [ "#launcher", "#HellYeah" ],
},
{
"Title" : "News 2",
"Description" : "news 2",
"FeaturesImage" : "",
"Author" : "Hutserino",
"Tags" : [ "#launcher", "#HellYeah" ]
}
]
}
我已经尝试过:
角度代码
<script>
(function() {
angular.module('myApp', []);
function myController($scope, $http) {
return $http.get('launcher.json')
.then(function(response) {
return response.data;
});
return {
LauncherTitle: LauncherTitle,
LauncherSlogan: LauncherSlogan
}
var data = response.data;
data.forEach(data.news, function(clientdata.news, index) {
angular.forEach(clientdata.news, function(newsitem, index){
$scope.news.push(newsitem);
});
});
}
})();
</script>
HTML
<div ng-app="myApp" ng-controller="myController">
<h1 class="display-3">{{ GameLauncherTitle }}</h1>
<h3 class="display-5">{{ GameLauncherSlogan }}</h3>
<div class="card-columns">
<div class="card" ng-repeat="newsitem in news">
<img src="{{ newsitem.FeaturesImage }}" class="card-img-top" alt="...">
<div class="card-body">
<h5 class="card-title text-dark">{{ newsitem.Title }}</h5>
<p class="card-text text-dark">{{ newsitem.Description }}</p>
</div>
</div>
</div>
</div>
但这不会返回任何结果。
答案 0 :(得分:0)
您将退出myController
函数并返回两个返回值,我想您可能一直在尝试
(function() {
var myApp = angular.module('myApp', []);
myApp.controller('myController', function($scope, $http) {
$scope.news = []
$http.get('launcher.json')
.then(function(r) {return JSON.parse(r)})
.then(function(response) {
response.news.forEach(function(newsitem){
$scope.news.push(newsitem);
});
});
});
})();
您可以尝试使用它代替Angular代码吗?
清洁版本:
(() => {
const myApp = angular.module('myApp', []);
myApp.controller('myController', ($scope, $http) => {
$scope.news = []
$http.get('launcher.json')
.then(r => JSON.parse(r))
.then(response => {
response.news.forEach(function (newsitem) {
$scope.news.push(newsitem);
})
})
})
})();