2013-11-21 26 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 }); });