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