javascript - 在 ng-repeat 子级之一中执行方法

标签 javascript angularjs github

我正在使用 Angular 的 ng-repeat 用来自 GitHub api 的数据填充表,我想要 <td> 之一执行将返回数据的方法。问题是这会使函数无限执行。

HTML:

      <table>
        <thead>
          <tr>
            <th>Name</th>
            <th>Languages</th>
          </tr>
        </thead>
        <tbody>
          <tr ng-repeat="repo in repos">
            <td>{{repo.name}}</td>
            <td></td> <!-- Get languages for each repo here. -->
          </tr>
        </tbody>
      </table>

Angular :

(function(){

  var app = angular.module("githubViewer", []);

  var MainController = function($scope, $http){

    var onUserComplete = function(response){
      $scope.user = response.data;
      $http.get($scope.user.repos_url)
          .then(onRepoComplete, onError);
    };

    var onRepoComplete = function(response){
      $scope.repos = response.data;
    };

    var onError = function(reson){
      $scope.error = "Could not fetch the data";
    };

    //search for user
    $scope.search = function(username){
      $http.get("https://api.github.com/users/" + username)
          .then(onUserComplete, onError);
    };

    // These two execute infinately if executed in the ng-repeat's <td>
    $scope.findLangs = function(langsUrl){
      $http.get(langsUrl)
        .then(onLangComplete, onError);
    }

    var onLangComplete = function(response){
      return response.data;
    };

  };

  app.controller("MainController", ["$scope", "$http", MainController]);

})();

我尝试在 <td> 中使用 {{ findLangs(repo.languages_url) }}但这导致我收到此错误:

Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!

并且似乎在无限执行。

最佳答案

我认为您不能在那里使用表达式,因为您实际上并未从 findLangs() 函数返回值。也就是说,我认为这不会导致无限循环。我认为您需要在 onRepoComplete 回调中实际获取每个存储库的语言数据,然后在模板中使用该数据:

var onRepoComplete = function(response){
  $scope.repos = response.data;
  $scope.repos.forEach(function(repo) {
    $http.get(repo.languages_url)
      .then(function(response) {
        // change this to process the language data however you need to...
        repo.languages = JSON.stringify(response.data);
      },onError);
  });
};

然后在您的模板中,您可以使用存储库的languages 属性:

<tr ng-repeat="repo in repos">
  <td>{{repo.name}}</td>
  <td>{{repo.languages}}</td>
</tr>

关于javascript - 在 ng-repeat 子级之一中执行方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39293813/

相关文章:

git - 为裸 repo 设置接收后 Hook

github - 发布新的 GitHub 页面

javascript - 如何将模型插入到特定索引中的backbone.js 集合中?

javascript - 当小部件紧密耦合在一起形成复杂模型时,找到在 raycaster 和相交的三个 js 中单击的确切元素

javascript - AngularJS 的时间范围 slider

javascript - Angular Material 设计有效/无效输入

javascript - 从多输入字段上传文件

带有基数 16 问题的 Javascript parseInt

angularjs - 绑定(bind)输入在 angularjs 中不集中

git - 在远程分支上运行 `git log`