2015-10-30 18 views
1

我想知道在我的頁面上需要注意什麼,然後才能應用特定的過濾器/轉換。要做到這一點,我正在使用$ watch,以便我知道這個值已被設置/設置。問題是我不知道在$ scope中需要注意哪個變量$ watch,因爲我使用外部庫來加載和設置變量。

如何打印出或準確找出手錶功能中正在監視哪些變量。目前,我有以下幾點:

$scope.$watch(function(){ 
    console.log("Variable Set"); 
}) 

我怎麼會做這樣的事情:

$scope.$watch(function(){ 
    console.log("watching: " + scopeItemModified); 
}) 

,這樣,當我點擊我的網頁上的項目,我可以清楚地看到什麼正在改變/觀看。

回答

1

沒有打印相同的變量是不可能的,但簡單你可以像這樣看整個範圍。

$scope.$watchCollection(function(){return $scope;},function(n,o){ 
    alert(o); 
    }) 
+0

感謝這正是我尋找。 – DeanMWake

0

你要做觀看範圍的一個變量,它會是這樣的:

$scope.nameOfVariableInScope = ''; 

$scope.$watch('nameOfVariableInScope', function(newValue, oldValue) { 
     console.log('Lets see the new value and the old value of my variable:'); 
     console.log(newValue, oldValue); 
}); 

希望它能幫助:)

+0

我理解這個概念,但如果你不加「nameOfVariableInScope '到$ watch你實際上可以觀察範圍內的每一個變化。我最終會補充說,所以我只聽一個特定的變量,但現在我不知道我想要聽的變量是什麼。我想用手錶找到那個變量 – DeanMWake

+0

嗯,我看到了...然後$ watchCollection()使用你的範圍對象或使用$ scope.myVars可以解決你的問題,看完整的對象 –

0

有了這個(真的),奇怪的角度破解我認爲它可以解決你的問題......

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

 
function MyCtrl($scope) { 
 
    $scope.first = '1'; 
 
    $scope.second = '2'; 
 
    $scope.objectField = { 
 
     third: '3' 
 
    }; 
 
    
 
    var scopeCloned = {} 
 
    
 
    $scope.$watchCollection(
 
     function(scope) { 
 
      
 
      //We compare each scope fields previoulsy copied 
 
      //If there is a change, we save that in console 
 
      angular.forEach(scope, function(value, key) { 
 
       if(key.substring(0, 1) != '$' && key != 'this') { 
 
        if(!angular.equals(scopeCloned[key],value)) { 
 
         var changes = { 
 
          field: key, 
 
          prevValue: scopeCloned[key], 
 
          newValue: value 
 
         } 
 
         console.log(changes); 
 
        } 
 
       } 
 
      }); 
 
      
 
      //We copy scope fields (without angular fields) to compare next time 
 
      angular.forEach(scope, function(value, key) { 
 
       if(key.substring(0, 1) != '$' && key != 'this') { 
 
       \t scopeCloned[key] = angular.copy(value); 
 
       } 
 
      }); 
 
     }, function() {} 
 
    ); 
 
};
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 

 
<div ng-app="myApp" ng-controller="MyCtrl"> 
 
    <input type="text" ng-model="first"/><br> 
 
    <input type="text" ng-model="second"/><br> 
 
    <input type="text" ng-model="objectField.third"/><br> 
 
</div>