如何在我设置它的函数之外使用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);
});
}
};
}]);
你的代码应该是工作,执行console.log调用将总是先totalData变量设置 – jusio
它打印空,因为它被称为确实有效,但是我怎样才能获得控制器底部的console.log,以便从$ http请求中更新我的总数,以便我可以使用它? – dynamo
只要您在控制器内发送请求,底部的console.log永远不会输出总计数。如果你想更新页数,你应该在回调中做到这一点。如果你想在另一个函数中做到这一点,你应该从回调 – jusio