0

I'm a new bee in the angularjs world. I was trying to use some pagination logic in my code.

While using $watch, my app is throwing TypeError: undefined is not a function on $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);   

      });
  }

and since I'm using controller as I didn't use the $scope, maybe that would be the case ?

Are there any opinions on using $scope vs controller as and since we on this what is recommendation $scope or controller as

Steve Mitcham
  • 5,268
  • 1
  • 28
  • 56
coljadu
  • 11
  • 1
  • 3

3 Answers3

0

$watch is a method of $scope so that's your problem. Solution is to inject $scope so you can use the $watch function on your object. See this question and answer: Angularjs: 'controller as syntax' and $watch

Community
  • 1
  • 1
iH8
  • 27,722
  • 4
  • 67
  • 76
0

Empdata is not an Angular object, it has no $watch method. You need to make it a property of the controller's $scope.

$scope.Empdata = {};
$scope.$watch('Empdata.currentPage + Empdata.numPerPage', function() { ... });
Terry
  • 14,099
  • 9
  • 56
  • 84
0

Whenever you want to use $watch when using controller as then you need explicitly bind this variable to scope using angular.bind

CODE

 $scope.$watch(angular.bind(Empdata, function () {
    return 'Empdata.currentPage + Empdata.numPerPage'; 
  }), function (newVal, oldVal) {
    // now we will pickup changes to newVal and oldVal
  });

Thanks

Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299