Arthur  Kishinets Arthur Kishinets - 4 months ago 15
AngularJS Question

$watch is not a function

I have angular directive that looks like this

app.directive('paymentsTable', ['$watch', function($watch) {
return {
replace: true,
restrict: 'EACM',
templateUrl: '../views/paymentTable.html',
link: function(elem, attr, scope) {

console.log(elem.$parent.payments); // array

scope.$watch(function(elem) { return elem.$parent.payments }, function(value, oldValue) {

});
}
};
}]);


It gives me


angular.js:13920Error: [$injector:unpr]


When I rewrite first line like this

app.directive('paymentsTable', [ function() {


It gives me another error


angular.js:13920TypeError: o.$watch is not a function


I also use uglify. So, my question is: what is going on here?

Answer

The $watch function is part of scope that is handed to you in the link method, therefore there is no need to inject it. The reason you get the second error is the order of the link arguments. Try it like this:

 app.directive('paymentsTable', function() { // no need for injection
    return {
      replace: true,
      restrict: 'EACM',
      templateUrl: '../views/paymentTable.html',
      link: function(scope, element, attrs) { // The correct arguments order

      console.log(elem.$parent.payments); 

      scope.$watch(function(elem) { return elem.$parent.payments }, function(value, oldValue) {

      });
    }
  };
});
Comments