Javascript 如何获取AngularJS中变量的侦听器?

Javascript 如何获取AngularJS中变量的侦听器?,javascript,angularjs,Javascript,Angularjs,在AngularJS中,我知道我可以将侦听器附加到如下变量: $scope.$watch("variableName", listenerFunc); 我想知道是否可以查询一个变量来找出哪些函数已经在监听它 具体来说,我想做如下的事情 if( listenerIsNotAlreadyAssigned("variableName",listenerFunc) ){ $scope.$watch("variableName", listenerFunc); // assign it

在AngularJS中,我知道我可以将侦听器附加到如下变量:

$scope.$watch("variableName", listenerFunc);
我想知道是否可以查询一个变量来找出哪些函数已经在监听它

具体来说,我想做如下的事情

if( listenerIsNotAlreadyAssigned("variableName",listenerFunc) ){
    $scope.$watch("variableName", listenerFunc);     // assign it
}

有没有办法用Angular实现上面的代码?如果是这样的话,怎么做?

这里有一种方法可能会被认为是有问题的

app.controller('myCtrl', function($scope) {    
  function checkWatchString(prop) {
    var found = false;
    angular.forEach($scope.$$watchers, function(item, i) {
      if (item.exp === prop) { found = true; }
    });
    return found;
  }

  $scope.$watch('foo', function() {

  });

  console.log(checkWatchString('bar')); //false
  console.log(checkWatchString('foo')); //true;
});
如果存储对创建手表的引用,则会得到取消手表的函数引用。您可以采取明显的方法,手动跟踪,并保持每个手表的取消功能可用

var app = angular.module('myApp', []);

app.controller('myCtrl', function($scope) {
  $scope.foo = '123';

  var reg = {};

  if (!reg.foo) {
    reg.foo = $scope.$watch('foo', function() {
      console.log('foo changed');
    });
  }
});
我用一个服务做了一个演示:

app.controller('myCtrl', function($scope) {    
  function checkWatchString(prop) {
    var found = false;
    angular.forEach($scope.$$watchers, function(item, i) {
      if (item.exp === prop) { found = true; }
    });
    return found;
  }

  $scope.$watch('foo', function() {

  });

  console.log(checkWatchString('bar')); //false
  console.log(checkWatchString('foo')); //true;
});
值班服务 加$watch 支票$watch 删除$watch
谢谢你的接受!我用一个演示更新了我的第一个服务方法,还添加了另一个方法。谢谢你的回答。这是一个很大的帮助!
watchService[prop] = $scope.$watch(prop, function() {
  ++$scope.changeCount;
});
if (watchService(prop)) {
watchService(prop, true);