【问题标题】:AngularJS $watch not working for pagination, giving undefined errorAngularJS $watch 不适用于分页,给出未定义的错误
【发布时间】:2015-03-17 21:44:59
【问题描述】:

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

在使用 $watch 时,我的应用在 $watch 上抛出 TypeError: undefined is not a function

  .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);   

      });
  }

因为我使用的是 controller as,所以我没有使用 $scope,也许是这样吧?

对于使用 $scope 与 controller as 有什么意见吗? 既然我们在这个 什么是推荐 $scope 或控​​制器为

【问题讨论】:

    标签: angularjs


    【解决方案1】:

    $watch$scope 的一种方法,所以这是你的问题。解决方案是注入$scope,以便您可以在对象上使用$watch 函数。看到这个问答:Angularjs: 'controller as syntax' and $watch

    【讨论】:

      【解决方案2】:

      Empdata 不是 Angular 对象,它没有 $watch 方法。您需要将其设为控制器 $scope 的属性。

      $scope.Empdata = {};
      $scope.$watch('Empdata.currentPage + Empdata.numPerPage', function() { ... });
      

      【讨论】:

        【解决方案3】:

        当您想在使用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 对你有帮助吗?
        猜你喜欢
        • 2022-10-01
        • 2015-03-14
        • 2015-01-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-12-26
        • 2016-11-03
        相关资源
        最近更新 更多