获取触发$ watch的object属性

时间:2014-01-14 14:40:07

标签: javascript angularjs

当您使用$ watch方法时(按值相等)。有没有办法查看哪个对象属性已更改?

e.g。

/**
                 * Save state of button: Cancelled
                 */
                $scope.$watch('buttons.cancelled', function(newValue, oldValue) {
                    if(newValue != oldValue && newValue !== undefined)  {
                        privates.viewState.buttons.cancelled = $scope.buttons.cancelled;
                    }
                });

                /**
                 * Save state of button: Booked
                 */
                $scope.$watch('buttons.booked', function(newValue, oldValue)    {
                    if(newValue != oldValue && newValue !== undefined)  {
                        privates.viewState.buttons.booked = $scope.buttons.booked;
                    }
                });

变成了;

        $scope.$watch('buttons', function(newValue, oldValue)   {
            if(newValue != oldValue && newValue !== undefined)  {
                //Is there a way to know which button triggered this watch?
            }
        }, true);

1 个答案:

答案 0 :(得分:1)

这是example

我还想看一个角度内置功能但是现在需要手动执行此功能

我将按钮放在对象数组中,而不是放在哈希键中,因为:

使用新值旧值调用

$ watch,只需比较它们:

$scope.buttons = [
  { name: 'cancelled', checked: false},
  { name: 'booked', checked: false},
  { name: 'something', checked: false}
];

$scope.$watch('buttons',function(newVal,oldVal){
  oldVal = oldVal.reduce(function(p,k){ p[k.name] = k.checked; return p;},{});

  var changed = newVal.filter(function(k){ 
    return oldVal[k.name] !== k.checked;
  });

  changed = changed.reduce(function(p,k){ p[k.name] = k.checked; return p;},{});

 $scope.changed = changed;

},true);