javascript - 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
但是更改时不会触发该事件
解决方案
使用深度手表:
$scope.$watch('currentScreen', function() {
console.log("screen changed");
̶}̶,̶ ̶f̶a̶l̶s̶e̶)̶;̶
}, true);
浅表 (with false
) 仅检查对象引用中的更改。deep watch (with true
) 检查内容的变化。
有关信息,请参阅AngularJS 开发人员指南 -$scope
观察深度。
推荐阅读
- reactjs - 使用 Navbar 和 LinkContainer 的动态链接
- git - 如何仅从父分支推送新更改
- kotlin - 是否有从某个位置在 ArrayList 中搜索的功能?
- google-cloud-firestore - 云数据存储中的 distinct on 子句是什么意思,它如何影响读取?
- swift - CAMetalLayer 初始化仅适用于主线程
- python - 我将如何切片字典中的键值
- json - VS 代码调试器无法找到 [Newtonsoft.Json.Schema.SchemaExtensions]::IsValid 的重载,即使它在 CLI 中工作也是如此
- azure - 使用 Outlook 2016 将 Azure 信息保护标签添加到 Powershell 脚本
- c# - 使用 AutoFixture 使用一组有限的字符之一填充对象属性
- javascript - 对象的 Redux 重新选择以字符串为键