$ watch不是一个功能

时间:2016-07-31 08:21:57

标签: javascript angularjs web

我有一个看起来像这样的角度指令

    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) {

      });
    }
  };
}]);

它给了我

  

angular.js:13920错误:[$ injector:unpr]

当我像这样重写第一行时

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

它给了我另一个错误

  

angular.js:13920TypeError:o。$ watch不是函数

我也使用uglify。所以,我的问题是:这里发生了什么?

1 个答案:

答案 0 :(得分:1)

$watch函数是scope的一部分,在link方法中传递给您,因此无需注入它。得到第二个错误的原因是link参数的顺序。试试这样:

 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) {

      });
    }
  };
});