0

我想在指令中的多個屬性上設置公共觀察者。我的代碼如下在角度上設置指令的多個屬性的觀察者

.directive('myDirective', function() { 
     return { 
      restrict: 'A', 
      scope: true, 
      link: function ($scope, element, attrs) { 
       $scope.$watch(function() { 
        return [attrs.attrOne]; 
       }, function (newVal) { 
        console.log(newVal); 
       }, true); 

    }) 

但這不起作用,我已經設置了對象相等的第三個參數爲true。但是,如果我嘗試設置觀察家上只是單個屬性,它工作正常,代碼如下

.directive('myDirective', function() { 
     return { 
      restrict: 'A', 
      scope: true, 
      link: function ($scope, element, attrs) { 
       $scope.$watch(attrs.attrOne, 
       function (newVal) { 
       console.log(newVal); 
       }); 
     }); 

誰能解釋這細節,爲什麼這種行爲發生如圖所示?

+0

@georgeawg,在普拉克你爲什麼要通過X與attr-一個= 「{{X}}」 爲什麼不ATTR一= 「X」,有沒有在這裏花括號 – madhur

回答

0

從AngularJS 1.3開始,有一個名爲$ watchGroup的新方法用於觀察一組表達式。

$scope.foo = 'foo'; 
$scope.bar = 'bar'; 

$scope.$watchGroup(['foo', 'bar'], function(newValues, oldValues, scope) { 
    // newValues array contains the current values of the watch expressions 
    // with the indexes matching those of the watchExpression array 
    // i.e. 
    // newValues[0] -> $scope.foo 
    // and 
    // newValues[1] -> $scope.bar 
}); 
+0

問題的任何具體原因是我在1.0.8上,所以這是不適用於我的使用 – madhur