我遇到了我的统计控制器的异步问题。我有一个控制器查询数据库并返回对象。在这个控制器中,我使用过滤器来获取平台Facebook的过滤器,并将其放入$rootScope.facebookObjects
。角度承诺
第一控制器:
app.controller('statsCtrl', function ($scope, $log, $http, $timeout, $filter, Data, $rootScope) {
Data.get('stats').then(function(data){
$scope.stats = data.data;
$scope.currentPage = 1; //current page
$scope.filteredItems = $scope.stats.length; //Initially for no filter
$scope.totalItems = $scope.stats.length;
$scope.list_pages = [
{
id: '5',
name: '5'
}, {
id: '10',
name: '10'
}, {
id: '20',
name: '20'
}, {
id: '50',
name: '50'
}, {
id: '100',
name: '100'
}
];
$scope.maxSize = 5;
$rootScope.facebookObjects = $filter('filter')($scope.stats, { platform: "facebook" });
$rootScope.twitterObjects = $filter('filter')($scope.stats, { platform: "twitter" });
});
$scope.setPage = function(pageNo) {
$scope.currentPage = pageNo;
};
$scope.filter = function() {
$timeout(function() {
$scope.filteredItems = $scope.filtered.length;
}, 10);
};
$scope.sort_by = function(predicate) {
$scope.predicate = predicate;
$scope.reverse = !$scope.reverse;
};
});
我有使用$rootScope.facebookObjects
来填充图表的第二控制器。问题是我需要等到$rootScope.facebookObjects
有一个值。目前我的控制台日志显示未定义。我正在看诺言,但我有点不确定哪个控制器使用它,以及如何正确使用它。
第二个控制器:
app.controller("PieCtrl", function ($scope, $rootScope, $timeout, $log) {
$log.log('facebook - '+$rootScope.facebookObjects.length);
});
如果你想分享控制器之间的数据没有数据连接到'$ rootScope',使用服务来代替。 – Ankh
我对角度很陌生。你能告诉我如何做到这一点? – Jason
尝试[类似这样的东西](http://stackoverflow.com/a/12513509/2043204) – Ankh