【发布时间】:2018-04-23 01:56:21
【问题描述】:
我是 Angular 的新手。我需要使用 AngularJS 1.6 从 JSON 文件呈现动态内容。这是我所拥有的。
News.json
{
"Articles": [
{
"Title": "News 1",
"Abstract": "News 1 abstract ...",
"Body": "News 1 starts here.... ",
"Comments": [
{
"comment 1" : "Comment 1 goes here",
"comment 2" : "Comment 2 goes here",
"comment 3" : "Comment 3 goes here"
}]
},
{
"Title": "News 2",
"Abstract": "News 2 abstract ... ",
"Body": "News 2 starts here...",
"Comments": [
{
"comment 1" : "Comment 1 goes here",
"comment 2" : "Comment 2 goes here"
}]
}
]
}
Script.js
app.config(function ($routeProvider) {
$routeProvider
.when("/News", {
templateUrl: "NewsViewer.html",
controller: "showNews"
});
});
app.controller("showNews", ["$scope", "$http", function ($scope, $http) {
$http({
method: 'GET',
url: 'News/News.json'
}).then(function success(data) {
$scope.News = data.data;
});
}]);
News.html
<div class="container-fluid">
<div class="row">
<div class="col-md-offset-1 col-md-6">
<div ng-controller="NewsRendering">
<div ng-repeat="NewsData in News.Articles">
<h3>{{NewsData.Title}}</h3>
<p>{{NewsData.Abstract}}</p>
<a data-ng-href="/AngularTask/NewsViewer.html">more</a>
</div>
</div>
</div>
<div class="col-md-4 questionnaire">
<h3>Questionnaire of the day</h3>
</div>
</div>
</div>
NewsViewer.html
<div class="container-fluid">
<div class="row">
<div class="col-md-offset-1 col-md-6">
<div ng-controller="showNews">
<div>
<h3>{{News.Articles[0].Title}}</h3>
<p>{{News.Articles[0].Abstract}}</p>
<p>{{News.Articles[0].Body}}</p>
</div>
<div class="comments">
<h4>Comments</h4>
<hr>
<p>{{News.Articles[0].Comments[0]}}</p>
</div>
</div>
</div>
</div>
</div>
此代码运行良好,但此代码不是动态的。我的问题是如何使其动态化并可以在 json 文件中显示任何内容。在JS代码中我应该怎么做才能传递JSON文件的数组的索引。
如您所见,<h3>{{News.Articles[0].Title}}</h3> 仅显示 JSON 文件的第一个标题。我需要写成<h3>{{News.Articles[index of whatever].Title}}</h3>
注意:News.json 有大约 100,000 条记录。我做了两个,只是为了显示代码和描述问题。
【问题讨论】:
-
看看 ng-repeat:w3schools.com/angular/ng_ng-repeat.asp(我不是官方 angular 文档的粉丝)。
-
您问题中的代码是运行问题所需的一切吗?我只看到 HTML 和一些 JSON。
-
@Rob 是的,我不太了解 angularjs,列表可能是 100,000 或更多
-
我根本看不到您在哪里提供了任何角度或 javascript 代码。您需要在此处发布问题代码的完整且最小的示例。 minimal reproducible example
-
好多了。每次都这样做。
标签: javascript html angularjs json