2017-06-07 2 views
0

これは、newsapiからデータを取得し、すべての結果を無限のスクロールパターンで表示する初めてのangleJSアプリケーションです。 データは取得されていますが、期待通りではありません。新しい結果は以前のものと重複し、ページあたり10個に制限されています。AngularJSはhttp.getの結果と重複し、ページあたり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

ソースの各ループで$ 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を使用し、各ソースを反復処理することができます。

あなたはすべての記事が1列にマージされ、あなたがアレイ用の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が1列にマージされています。

+0

ありがとうIgor、プッシュメソッドは私のニーズに働いた。 concatメソッドは空の配列を返しましたが – Ronit

関連する問題