【问题标题】:using ng-repeat with api json in a for-loop在 for 循环中使用 ng-repeat 和 api json
【发布时间】:2017-07-18 03:52:40
【问题描述】:

我正在使用 angularjs 开发一个迷你应用程序,该应用程序将从新闻 api 中获取数据。我已经成功地使用 for 循环(如下)从 10 个新闻源(全部由 api 提供)数组中获取了 10 篇文章(只是我想要的数量)。问题是视图中的 ng-repeat 只显示循环的最后一次迭代。我怎样才能让它显示所有的迭代?

这里是控制器:

angular.module('newsApp',[])
  .controller('newsController',['$scope','$http', function($scope,$http){

    var index = 0;
    var sortby = ['top','latest','popular'];

    $http.get('https://newsapi.org/v1/sources?language=en').then(function(response){
      var sourceIdArray = [];
      var articlesArray = [];

      for (var i = 0; i < 9; i++) {
        $scope.getId = response.data.sources[i].id;
        sourceIdArray.push($scope.getId);




         $http.get(' https://newsapi.org/v1/articles?source=' + sourceIdArray[i] + '&apiKey=53bec2b512724f58b92203f0f7e93dc1').then(function(response){
        $scope.comits = response.data.articles
        articlesArray.push($scope.comits);
      });

      }


    })



  }])

循环为我提供了所有必需的文章,但我不知道如何编写 ng-repeat 来显示所有数据而不是仅显示最后一次迭代

和html:

<div class="row rowdiv" ng-repeat="comit in comits" ng-if="$index % 2 == 0">
        <div class="col-md-6">
          <img ng-src="{{comits[$index].urlToImage}}" alt="">
          <h3><a ng-href="{{comits[$index].url}}">{{comits[$index].title}}</a></h3>
          <p>{{comits[$index].description}}</p>
          <h5>{{result}}    {{comits[$index].author}}</h5>
          <h6 class="pull-right">{{comits[$index].publishedAt}}</h6>


        </div>

        <div class="col-md-6">
          <img ng-src="{{comits[$index +1].urlToImage}}" alt="">
          <h3><a ng-href="{{comits[$index +1].url}}">{{comits[$index +1].title}}</a></h3>
          <p>{{comits[$index + 1].description}}</p>
          <h5>{{result}}   {{comits[$index + 1].author}}</h5>
          <h6 class="pull-right">{{comits[$index +1].publishedAt}}</h6>


        </div>

      </div>

任何帮助将不胜感激!

【问题讨论】:

  • 使用模板中的comit而不是comits[$index]引用ng-repeat中的当前项目。
  • 我已经试过了,但是没用
  • ng-repeat 的这种用法效率很低。对于一个包含 10 个项目的数组,您将遍历该数组 10 次,并在一半的循环中输出接下来的两个项目,这意味着您实际上最终会为 10 个项目访问该数组 20 次。

标签: angularjs arrays api for-loop angularjs-ng-repeat


【解决方案1】:

您正在使用articlesArray.push($scope.comits); 将文章推送到articlesArray 中

您需要将articlesArray 设为$scope 的成员,然后使用ng-repeat 访问它。 $scope.comits 仅包含根据您的代码检索到的最后一篇文章。

或者将提交声明为 $scope.comits = [] 然后将 $scope.comits = response.data.articles 更改为 $scope.comits.push(response.data.articles)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-10
    • 1970-01-01
    • 2016-07-05
    • 1970-01-01
    • 2016-09-03
    • 1970-01-01
    相关资源
    最近更新 更多