【发布时间】:2023-03-22 13:28:01
【问题描述】:
这个问题实际上是在我用 AngularJS 1.6.10 编写时发生的,但我认为 $timeout 在某种程度上是 setTimout,所以我提到了两者。
长话短说,我有两个divs 可以根据使用ng-if 的条件进行切换
<div ng-if="!vm.isDrillDowned" id="{{vm.segContainerId}}" style="height: 100%; width: 100%;"></div>
<div ng-if="vm.isDrillDowned" id="{{vm.drillDownContainerId}}" style="height: 100%; width: 100%;">
控制ng-if条件的代码是:
public renderReport(filters){
if (//some condition) {
reportId = this.drillDownId;
containerId = this.drillDownContainerId;
this.isDrillDowned = true;
}
if (//some condition) {
reportId = this.segId;
containerId = this.segContainerId;
this.segmentFilter = null;
this.isDrillDowned = false;
}
//Expect $timeout to refresh UI showing one div, then runs this.render()
this.$timeout(() => this.render(reportId, containerId, filtersCopy));
}
this.render()
public render(reportId: string, containerId: string, filters?: any) {
const container = document.querySelector(`#${containerId}`);
this.$window.ThirdPartySDK.renderReportPart(container, /*other parameters */);
}
当我调试的时候,有时当代码在$timeout里面碰到函数时,我可以看到isDrilledDown被改变了,但是ng-if还没有刷新视图,所以querySelector可以'找不到与containerId相关的DOM元素。
根据 JS 的事件循环和 $timeout/setTimeout 的机制,我假设 this.render 只会在 UI 更新后运行,但有时并非如此。 ng-class 在另一个地方也发生了同样的问题,在 $timeout 内运行时元素类不会更新。
我只是想知道在某些极端情况下这种行为是否可能?我所搜索的只是说 $timeout/setTimeout 将在 UI 更新后运行它的回调。
提前致谢!
【问题讨论】:
标签: javascript angularjs settimeout