我正在使用$ watch来查看我页面中的数据分页。但是在我点击任何按钮之前它没有显示数据
这是代码。
.controller('AppCtrl', function ($scope, $modal, Faq) {
$scope.filteredFaqData = [];
$scope.currentPage = 1;
$scope.numPerPage = 5;
$scope.maxSize = 5;
$scope.faqData = [];
$scope.faqData = Faq.getFaqs();
$scope.$watch('currentPage + numPerPage', function () {
var begin = (($scope.currentPage - 1) * $scope.numPerPage)
, end = begin + $scope.numPerPage;
$scope.filteredFaqData = $scope.faqData.slice(begin, end);
});
})
我从服务中获取 $ scope.faqData 中的数据。但 $ scope.filteredFaqData 为空,直到我点击分页标签
答案 0 :(得分:0)
也许这会解决问题:
.controller('AppCtrl', function ($scope, $modal, Faq) {
//create function that can be called on several places
var updateFilteredData = function () {
var begin = (($scope.currentPage - 1) * $scope.numPerPage),
end = begin + $scope.numPerPage;
$scope.filteredFaqData = $scope.faqData.slice(begin, end);
};
$scope.filteredFaqData = [];
$scope.currentPage = 1;
$scope.numPerPage = 5;
$scope.maxSize = 5;
$scope.faqData = Faq.getFaqs();
$scope.$watchGroup(['currentPage', 'numPerPage'], function () {
//call on update
updateFilteredData();
});
//initial call
updateFilteredData();
});
注意:最好使用watchGroup
,因为这是做你想做的事情的方式(documentation)。
答案 1 :(得分:0)
实际上我的函数 Faq.getFaqs()是异步执行的。当页面第一次加载时,没有数据显示。所以我使用$ timeout来消耗$ watch,现在它正在运行。
这是代码
$scope.filteredFaqData = [];
$scope.currentPage = 1;
$scope.numPerPage = 5;
$scope.maxSize = 5;
$scope.faqData = [];
$scope.faqData = Faq.getFaqs();
$timeout(function lateDisplay(){
$scope.$watchGroup(['currentPage','numPerPage'], function (newValues, oldValues, scope) {
var begin = ((newValues[0] - 1) * newValues[1])
, end = begin + newValues[1];
$scope.filteredFaqData = $scope.faqData.slice(begin, end);
});
},100);