JanRad JanRad - 3 months ago 9
Javascript Question

Execute method in one of ng-repeat child

I'm using angular's ng-repeat to populate table with data from GitHub api and I want one of the to execute method that will return data. the problem is that this makes the function execute infinitely.

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]);

})();


I've tried using {{ findLangs(repo.languages_url) }} in the but it causes me to get this error:


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


and appears to be infinitely executing.

Answer

I don't think you can use an expression there because you don't actually return a value from the findLangs() function. That said, I don't think that would cause an infinite loop. I think you'll need to actually grab the language data for each repo within the onRepoComplete callback, then just use that data in your template:

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);
  });
};

Then in your template you can use the languages property of the repo:

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