首页 > 解决方案 > scope.$watch 不会与散列对象(关联数组)一起触发?

问题描述

我的范围有问题。$watch,我有两个组件和一个控制器,在第一个组件中我可以选中一些复选框,当我选中这些复选框时,我会更新一个包含所有选中对象的变量:

scope.values[well].selected = !scope.values[well].selected;
if (!scope.selectedWells.includes(scope.values[well])) {
  scope.selectedWells.push(scope.values[well]);
} else {
  var index = scope.selectedWells.indexOf(scope.values[well]);
  if (index > -1) {
     scope.selectedWells.splice(index, 1);
  }
}

使用此代码,它运行良好,当我修改我的 selectedWells 对象时,在我的第二个组件中,事件是 catch :

scope.$watch('selectedWells', reloadLegend, true);

问题是我需要使我的 selectedWells 对象成为一个哈希对象(关联数组),才能拥有如下所示的内容:

{
  'wellNumber1' : {}
}

所以我将我的代码编辑为:

scope.values[well].selected = !scope.values[well].selected;

// Add or remove from the selectedWells
if (!scope.selectedWells[well]) {
  scope.selectedWells[well] = scope.values[well];
} else {
  delete scope.selectedWells[well];
}

它在第一个组件中也很有效,但我的事件不再被捕获。

为什么这适用于“简单”数组而不适用于关联数组?

编辑 :

这是我的问题的第二个例子:

var currentScreen = {};
$scope.$watch('currentScreen', function() {
  console.log("screen changed");
}, false);

/**
 * Get a screen by id
 * @param id
 */
function getDefaultScreen(id) {
  $timeout(function () {
    ScreensService.customShow('get', 'example')
      .then(getScreen)
      .catch(getScreenFailed);

    function getScreen(data) {
      console.log(data);
      currentScreen = data;
    }

    function getScreenFailed(e) {
      ...
      return $q.reject(e);
    }
  });
}

获取屏幕返回一个像这样的对象:{A01: {…}, A02: {…}, A03: {…}, A04: {…}, A05: {…}, …}

currentScreen但是更改时不会触发该事件

标签: javascriptarraysangularjs

解决方案


使用深度手表:

$scope.$watch('currentScreen', function() {
  console.log("screen changed");
̶}̶,̶ ̶f̶a̶l̶s̶e̶)̶;̶
}, true);

浅表 (with false) 仅检查对象引用中的更改。deep watch (with true) 检查内容的变化。

有关信息,请参阅AngularJS 开发人员指南 -$scope观察深度


推荐阅读