2013-11-21 25 views
0

我想创建一个无限滚动列表angularjs中的列表。为此,我需要从api获取新数据,然后将其附加到angularjs中作用域的现有结果中。我已经尝试了几种方法,但是迄今为止它们都没有工作。
目前,这是我的控制器:从restful api添加新的数据到angularjs范围

userControllers.controller('userListCtrl', ['$scope', 'User', 
    function($scope, User) { 
     $scope.users = User.query(); 
     $scope.$watch('users'); 
     $scope.orderProp = 'name'; 
     window.addEventListener('scroll', function(event) { 
      if (document.body.offsetHeight < window.scrollY + 
        document.documentElement.clientHeight + 300) { 
       var promise = user.query(); 
       $scope.users = $scope.users.concat(promise); 
      } 
     }, false); 
    } 
]); 

这是我的服务:

userServices.factory('User', ['$resource', 
    function($resource) { 
     return $resource('api/users', {}, { 
      query: { 
       method: 'GET', 
       isArray: true 
      } 
     }); 
    } 
]); 

我如何追加新结果的范围,而不是取代旧的?

回答

0

下面的代码的伎俩:

$scope.fetch = function() { 
    // Use User.query().$promise.then(...) to parse the results 
    User.query().$promise.then(function(result) { 
     for(var i in result) { 
      // There is more data in the result than just the users, so check types. 
      if(result[i] instanceof User) { 
       // Never concat and set the results, just append them. 
       $scope.users.push(result[i]); 
      } 
     } 
    }); 
}; 

window.addEventListener('scroll', function(event) { 
    if (document.body.offsetHeight < window.scrollY + 
      document.documentElement.clientHeight + 300) { 
     $scope.fetch(); 
    } 
}, false); 
0

我认为你可能需要使用$ scope.apply() 当承诺返回时,因为它不是 角度执行循环的一部分。 尝试类似: User.query()。then(function(){ $ scope.apply(function(result){ // concat new users }); });