AngularJS重叠http.get结果并将其限制为每页10个

时间:2017-06-07 21:14:08

标签: angularjs angularjs-ng-repeat angularjs-controller

这恰好是我的第一个angularJS应用程序,它从newsapi获取数据并以无限滚动模式显示所有结果。 我收到数据但不是预期的,新的结果与之前的结果重叠,每页限制为10个。

如果我做错了,请建议。

<!DOCTYPE html>
<html>
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">

<script 
 src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js">
</script>

<body>
<div class="w3-container" ng-app="myApp" ng-controller="myCtrl">
<p>Today's News:</p>
<div class="w3-card-4" style="width:100px margin:20px" ng-repeat="x in 
source">
<img src="{{x.urlToImage}}" style="width:100%">
<div class="w3-container w3-center">
<h2><a href="{{x.url}}" target="_blank">{{x.title}}</a></h2>
</div>
</div><br><br>
</div>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
var websites = ["the-times-of-india", "google-news", "bbc-news", "mirror", 
"reuters", "the-hindu", "the-new-york-times", "the-wall-street-journal"];
for(var i=0; i<websites.length;i++){
$http.get("https://newsapi.org/v1/articles?source=" +websites[i] 
+"&apiKey=f483fa2a3f714981afbee1a1996545b4")
.then(function(response) {
$scope.source = response.data.articles;
});
}
});
</script>

</body>
</html>

1 个答案:

答案 0 :(得分:1)

您在源上的每个循环中覆盖$ scope.source。如果您需要获取所有来源,可以将其推送到一系列来源:

app.controller('myCtrl', function($scope, $http) {
  var websites = ["the-times-of-india", "google-news", "bbc-news", "mirror", 
    "reuters", "the-hindu", "the-new-york-times", "the-wall-street-journal"];
  $scope.sources=[];
  for(var i=0; i<websites.length;i++){
    $http.get("https://newsapi.org/v1/articles?source=" +websites[i] 
    +"&apiKey=f483fa2a3f714981afbee1a1996545b4")
    .then(function(response) {
      $scope.sources.push(response.data.articles);
    });
  }
})

然后,您可以使用$ scope.sources并遍历每个源。

如果您需要在一个数组中合并所有文章,则可以对数组使用concat()方法:

app.controller('myCtrl', function($scope, $http) {
  var websites = ["the-times-of-india", "google-news", "bbc-news", "mirror", 
    "reuters", "the-hindu", "the-new-york-times", "the-wall-street-journal"];
  $scope.source=[];
  for(var i=0; i<websites.length;i++){
    $http.get("https://newsapi.org/v1/articles?source=" +websites[i] 
    +"&apiKey=f483fa2a3f714981afbee1a1996545b4")
    .then(function(response) {
      if (response.data.articles){
         $scope.source.concat(response.data.articles);
      }
    });
  }
})

现在你有一个$ scope.source,所有文章都合并到一个数组中。