0

I saw other questions about this but didn't helped me.

I have function in angularjs controller:

$scope.getUser = function(id){
    ret = null;
    $http.get('services/rest/users/' + id).then(
        function(response){
            ret = response.data.name;
        }, 
        function(response){
        }
    )
        return ret;
} 

And I call that function in html:

<div ng-repeat = "move in moves">Player:<span> {{getUser(move.player_id)}} </span> - {{move.guess}} - {{move.answer}}</div>

And this creates infinite loop of 'services/rest/users/' + id requests. I saw that angular can do this when some object in scope is always changing, but I don't see this here.

4
  • Isn't it due to digest cycle getting called again and again whenever your one request (backend) is getting completed? That can call ng-repeat directive again. Commented May 28, 2017 at 18:45
  • 2
    First, make get user a promise using $q and resolve if response or reject if error. Second, it is a bad practice to call multiple http requests in ng-repeat. Bring your data in one request if you can and when the data is ready, populate an array binded to the moves scope variable. Commented May 28, 2017 at 18:45
  • 1
    It loops even without ng-repeat. I called that function from another place and it started looping again. Will try with $q. Commented May 28, 2017 at 18:50
  • 1
    Never use functions in view that make asynchronous requests. Commented May 28, 2017 at 19:02

1 Answer 1

4

Approach is all wrong.

$http is asynchronous and ret will always be null when returned from getUser()

Never use functions in view that directly make asynchronous requests.

Instead, in controller( or better yet in service) iterate all your moves , request player data , and add that as property of each move

function getUser(id) {
  return $http.get('services/rest/users/' + id).then(function(response) {
    return response.data.name;
  }).catch(function() {
    return 'Unknown Player';
  })
}


angular.forEach($scope.moves, function(move){
   getUser(move.player_id).then(function(player){
      move.player = player;
   });
});

View:

<div ng-repeat = "move in moves">Player:<span> {{move.player)}} </span>...</div>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.