AngularJS use a function in a controller to return data from a service to be used in ng-repeat

痞子三分冷 提交于 2019-11-30 19:31:29

This is about $digest, $watch and ng-repeat. You can find a lot of answers by simply googling it or check out link given by Jsplaine.

In short, your getListUsers() function returns a list of Users every time it is called. However, every returned list is a new collection ( array ). To angular, this means it has to update the display of the list on the page. After each update, Angular actually check a few times to see if the list becomes stable or not by calling getListUsers() function again. Every time angular found that the list is different, so it keep updating the list and keep calling the getListUser function.

To solve this problem, you can create a variable holding the user list:

 $scope.userList = [];

and also the function to update the list

$scope.reloadListUsers = function(){
    User.listUsers().then(function(response){
        $scope.userList = response.users;
    });
}

Then in the ng-repeat directive

<div ng-repeat="user in userList">{{ user.somedata }}</div>

Where you want to reload the list, simple call the reloadListUsers function .

<button ng-click="reloadListUsers()" > reload </button>

The reason behind is that now the variable userList is used in the binding instead of the function call expression, and it becomes stable once the list is loaded.

There's a few problems. You're returning a value from an anonymous function that is invoked when the promise returned from the $http.get call is resolved. The return value of that function will not be the value returned from getListUsers.

Also, you're referencing response.users in the controller callback. That is still the raw response object. You may have meant to reference response.data.users?

Try this:

elite.controller('UserController', function($scope, User){

$scope.users = [];

$scope.getListUsers = function(){
    User.listUsers().then(function(response){
        $scope.users = response.data.users;
    });
}

});

elite.factory('User', function($http){
 var User = {
  getUser: function(id){
      return $http.get('/user/' + id + '/settings');
  },
  listUsers: function(){
    return $http.get('/user/');
   }
}
  return User;
});

Then, bind it in the view:

<div ng-repeat="user in users">{{ user.somedata }}</div>

The ng-repeat directive will not spit out any elements if users is undefined or empty.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!