Angular.js:存储http.get请求中的变量,以便在不同的$scope函数中全局使用

Angular.js: Storing variable from http.get request to use globally in different $scope function

本文关键字:scope 全局 函数 存储 js http get Angular 变量 请求      更新时间:2023-09-26

我正在尝试在我的Ionic/Cordova移动应用程序中实现无限滚动。我的nextBatch变量保存用户点击页面底部后需要获取的下一组对象的url。唯一的问题是,当我试图在loadMoreData()函数中访问它时,它显示为未定义。我尝试过使用$rootScope,但得到了相同的结果。你知道我该怎么处理吗?

谢谢!

.controller('HomeCtrl', function($scope,Model) {
        var nextBatch; //holds the url of the next batch
        $scope.model = []; //used in ng-repeat
        //loads an array of 5 objects
        Model.getAll().success(function(model){
            nextBatch        = model.meta.next; //for infinite scrolling 
            $scope.model     = model.objects; 
        })
        $scope.loadMoreData = function() {
            if (nextBatch !== undefined) {
                Model.getMore(nextBatch).then(function(model){
                   $scope.model.push(favours);
                   $scope.$broadcast('scroll.infiniteScrollComplete');
                })      
            }
};
 })

以下是如何同步您的无限滚动。我的意思是在第一次调用(getAll完成)之前阻止loadMore。

.controller('HomeCtrl', function($scope, Model, $q) {
  var nextBatch; //holds the url of the next batch
  $scope.model = []; //used in ng-repeat
  var defer = $q.defer();
  var promise = defer.promise;
  //loads an array of 5 objects
  Model.getAll().then(function(model){
      nextBatch        = model.meta.next; //for infinite scrolling 
      $scope.model     = model.objects;
      defer.resolve(model);
      return defer.promise;
  });
  $scope.loadMoreData = function() {
      promise.then(function(result){
          if(nextBatch !== "END"){
            Model.getMore(nextBatch).then(function(favours){
              angular.forEach(favours.objects, function(item){
                $scope.model.push(item);
              });
              nextBatch = favours.meta.next;
            });
          }    
      });
  };
})

http://plnkr.co/edit/qohKNUd48czYKASNqCVP