AngularJS$watch不适用于分页,给出未定义的错误
我是安格拉斯世界里的一只新蜜蜂。我试图在代码中使用一些分页逻辑 使用$watch时,我的应用程序抛出AngularJS$watch不适用于分页,给出未定义的错误,angularjs,Angularjs,我是安格拉斯世界里的一只新蜜蜂。我试图在代码中使用一些分页逻辑 使用$watch时,我的应用程序抛出TypeError:undefined不是$watch上的函数 .controller("EmployeeListCtrl", ["employeeResource", EmployeeListCtrl]); function EmployeeListCtrl(employeeResource) { var Empdata = this; Empdata.empl
TypeError:undefined不是$watch上的函数
.controller("EmployeeListCtrl", ["employeeResource", EmployeeListCtrl]);
function EmployeeListCtrl(employeeResource) {
var Empdata = this;
Empdata.employeePerPage = [];
employeeResource.query(function(data){
Empdata.employee = data;
});
Empdata.currentPage = 1;
Empdata.numPerPage = 10;
Empdata.maxSize = 5;
Empdata.numPages = function() {
return Math.ceil(Empdata.employee.length / Empdata.numPerPage);
};
Empdata.$watch('Empdata.currentPage + Empdata.numPerPage', function() {
var start = ((Empdata.currentPage - 1) * Empdata.numPerPage),
end = start + Empdata.numPerPage;
Empdata.employeePerPage = Empdata.employee.slice(begin, end);
});
}
既然我使用的是控制器,因为我没有使用$scope,也许会是这样
对于使用$scope vs controller作为
既然我们在这件事上
什么是推荐
$scope或controller as
是$scope
的一种方法,所以这就是您的问题所在。解决方案是注入$scope
,这样您就可以在对象上使用$watch
函数。查看此问题和答案:Empdata
不是角度对象,它没有$watch
方法。您需要使其成为控制器的$scope
的属性
$scope.Empdata = {};
$scope.$watch('Empdata.currentPage + Empdata.numPerPage', function() { ... });
当使用controller as
时,只要您想使用$watch,就需要使用angular.bind将此变量显式绑定到作用域
代码
$scope.$watch(angular.bind(Empdata, function () {
return 'Empdata.currentPage + Empdata.numPerPage';
}), function (newVal, oldVal) {
// now we will pickup changes to newVal and oldVal
});
谢谢@coljadu这对你有帮助吗?