Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/431.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 获取触发$watch的对象属性_Javascript_Angularjs - Fatal编程技术网

Javascript 获取触发$watch的对象属性

Javascript 获取触发$watch的对象属性,javascript,angularjs,Javascript,Angularjs,使用$watch方法时(值相等)。是否有办法查看哪个对象属性已更改 e、 g 变成, $scope.$watch('buttons', function(newValue, oldValue) { if(newValue != oldValue && newValue !== undefined) { //Is there a way to know which button triggered thi

使用$watch方法时(值相等)。是否有办法查看哪个对象属性已更改

e、 g

变成,

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

我还希望看到一个角度内置功能,但现在您需要手动执行该操作

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

  • 哈希键更难迭代和转换
  • 我使用的是ng型号
$watch使用新值和旧值调用,只需比较它们:
嗯,您有
newValue
oldValue
,所以您必须自己进行比较(
if(newValue.booked!==oldValue.booked){booked changed!'
)。
        $scope.$watch('buttons', function(newValue, oldValue)   {
            if(newValue != oldValue && newValue !== undefined)  {
                //Is there a way to know which button triggered this watch?
            }
        }, true);
$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);