Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/delphi/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
AngularJS$watch不适用于分页,给出未定义的错误_Angularjs - Fatal编程技术网

AngularJS$watch不适用于分页,给出未定义的错误

AngularJS$watch不适用于分页,给出未定义的错误,angularjs,Angularjs,我是安格拉斯世界里的一只新蜜蜂。我试图在代码中使用一些分页逻辑 使用$watch时,我的应用程序抛出TypeError:undefined不是$watch上的函数 .controller("EmployeeListCtrl", ["employeeResource", EmployeeListCtrl]); function EmployeeListCtrl(employeeResource) { var Empdata = this; Empdata.empl

我是安格拉斯世界里的一只新蜜蜂。我试图在代码中使用一些分页逻辑

使用$watch时,我的应用程序抛出
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这对你有帮助吗?