2014-10-16 66 views
4

如果我動態註冊手錶事件(在我的情況下爲for循環),角度不起作用。請看一下小提琴。有任何想法嗎?角度:手錶不工作內部循環

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


function MyCtrl($scope, $parse) { 

    // 1. binding watch inside loop (doesn't work): 
    $scope.aaa = 1; 
    $scope.bbb = 2; 

    $scope.dependsOn = [ 
     function() { return $scope.aaa; }, 
     function() { return $scope.bbb; } 
    ];   

    for (var i = 0; i < $scope.dependsOn.length; i++) {   

     $scope.$watch(
      function() { 
       return $scope.dependsOn[i];      
      }, 
      function (newVal) { 
       if (newVal !== undefined) { 
        console.log("doesn't work"); 
       } 
      } 
     ); 
    }  

    $scope.aaa = 5; 
    $scope.bbb = 6;  

    // binding watch not inside loop (works): 

    $scope.ccc = 1; 
    $scope.ddd = 2;  

    $scope.dependsOn = [ 
     function() { return $scope.ccc; }, 
     function() { return $scope.ddd; } 
    ];  

    $scope.$watch(
     function() { 
      return $scope.dependsOn[0];      
     }, 
     function (newVal) { 
      if (newVal !== undefined) { 
       console.log("works"); 
      } 
     } 
    );  

    $scope.$watch(
     function() { 
      return $scope.dependsOn[1];      
     }, 
     function (newVal) { 
      if (newVal !== undefined) { 
       console.log("works"); 
      } 
     } 
    );  

    $scope.ccc = 5; 
    $scope.ddd = 6;  
} 

fiddle

回答

9

您所遇到的問題是因爲你捕捉一個封閉的可變i。然後i會增加到值2並退出循環,在您實際執行委託時,您的每位代表都將擁有2個值作爲它們的i值。

演示: http://jsfiddle.net/df6L0v8f/1/ (增加:)

$scope.$watch(
    function() { 
     console.log(i); 
     return $scope.dependsOn[i];      
    }, 
    function (newVal) { 
     if (newVal !== undefined) { 
       console.log("doesn't work"); 
     } 
    } 
); 

您可以通過使用自閉打電話來捕捉在迭代的時間價值,並堅持認爲,解決這一問題及可變提升的問題你代表。

http://jsfiddle.net/df6L0v8f/4/

for (var i = 0; i < $scope.dependsOn.length; i++) {   
    var watchDelegate = (function(itemDelegate){ 
      return function() { 
       return itemDelegate;      
      }; 
     })($scope.dependsOn[i]); 

     $scope.$watch(
      watchDelegate, 
      function (newVal) { 
       if (newVal !== undefined) { 
        console.log(newVal()); 
       } 
      } 
    ); 
    }