0

如何在我设置的函数之外使用 totalResults?我只是不知道该怎么做,我需要使用从数据库中收集的 totalResults 并在另一个函数中使用来计算页面数量。我这样做是为了不将所有数据加载到客户端,但我仍然需要知道数据库表中的总行数。

我的 json 看起来像:

Object {total: 778, animals: Array[20]}

角度:

var app = angular.module('app', []);

app.controller('AnimalController', ['$scope', 'animalSrc', function($scope, animalSrc)
{
    $scope.animals = [];

    var skip = 0;
    var take = 20;
    var totalResults = null;
    //$scope.totalResults = null;

    $scope.list = function()
    {
        animalSrc.getAll(skip, take, function(data) {
            $scope.animals = $scope.animals.concat(data.animals);

            // I need to be able to use this outside of function ($scope.list)
            totalResults = data.total;
            //$scope.totalResults = data.total;
        });
    };

    $scope.showMore = function()
    {
        skip += 20;
        $scope.list();
    };

    $scope.hasMore = function()
    {
        //
    };

    // Outputs null, should be the total rows from the $http request
    console.log(totalResults); 
}]);

app.factory('animalSrc', ['$http', function($http)
{
    // Private //

    return {
        getAll: function(skip, take, callback)
        {
            $http({
                method: 'GET',
                url: 'url' + skip + '/' + take
            }).
            success(function(data) {
                callback(data);
            }).
            error(function(data) {
                console.log('error: ' + data);
            });
        }
    };
}]);
4

2 回答 2

1

这是我刚刚为自己编写的类似设置的样板,其中数据是一个需要拆分为多个范围项的对象。您没有掌握的问题是将数据存储在服务中,而不仅仅是使用服务来检索数据。然后通过注入服务,数据项可跨多个控制器和指令使用

app.run(function(MyDataService){
  MyDataService.init();
})

app.factory('MyDataService',function($http,$q){

  var myData = {
    deferreds:{},

    mainDataSchema:['count','items'],
    init:function(){
      angular.forEach(myData.mainDataSchema,function(val,idx){ 
        /* create deferreds and promises*/
        myData.deferreds[val]=$q.defer();
        myData[val]= myData.deferreds[val].promise
      });     
      /* load the data*/
      myData.loadData();

    },     

    loadData:function(){
         $http.get('data.json').success(function(response){
           /* create resolves for promises*/
           angular.forEach(myData.mainDataSchema,function(val,idx){            
             myData.deferreds[val].resolve(response[val]);
        });
       /* TODO -create rejects*/

      })

    }
  }

  return myData;

  })

app.controller('Ctrl_1', function($scope,MyDataService ) {
    $scope.count = MyDataService.count;
    $scope.items =MyDataService.items;
});

app.controller('Ctrl_2', function($scope,MyDataService ) {
  $scope.items =MyDataService.items;
  $scope.count = MyDataService.count;
});

Plunker 演示

于 2013-04-14T02:42:44.613 回答
1

你需要开始异步思考。您的 console.log 在 $http 返回并设置 totalResults 之前被调用。因此,totalResults 将始终为空。

您需要找到一些方法来延迟对console.log 的调用,以便在运行console.log 之前完成$http 调用。一种方法是将console.log 调用放在回调函数中,以便在$http 成功后肯定会调用它。

一个更优雅的方法是使用 Promise。angular.js 实现了 $q,它类似于一个 Promise 库 Q。

http://docs.angularjs.org/api/ng.$q

您无需在 getAll 中创建回调函数,而是返回一个 Promise。在 $http success 中,您使用数据解决了 Promise。然后,在您的控制器中,您有一个在解决承诺时调用的函数。Promise 很好,因为它们可以被传递,并且它们允许您控制异步代码的流程而不会阻塞。

于 2013-04-14T00:45:14.120 回答