gpt4 book ai didi

javascript - Angular 2 - 替代 $scope.$apply?

转载 作者:太空狗 更新时间:2023-10-29 16:53:05 24 4
gpt4 key购买 nike

$scope.$apply 将不再是 Angular 2 的一部分。如果任何绑定(bind)属性在常规 Angular 执行上下文之外发生更改,我们如何让 Angular 知道更新 DOM ?

取自a blog post by Minko Gechev :

No more $scope.$apply

But how then AngularJS knows that anything outside it’s execution context has taken a place? Lets think where the changes might come from:

  • setTimeout
  • setInterval
  • prompt (yeah, there are people who still use it…)
  • XMLHttpRequest
  • WebSockets

答案是:

enter image description here

我知道修补浏览器内置的 javascript 函数以通知 Angular 的任何更改是可以以相对安全的方式完成的(不会引入细微的错误)并且对开发人员来说非常方便。但是第三方 API(例如 jQuery.fadeIn)或者如果浏览器公开了一些未涵盖的新异步 API 怎么办?旧的 $scope.$apply 的替代品是什么?

最佳答案

  1. 从核心导入NgZone
  2. 私有(private)区域:构造函数中的 NgZone
  3. this.zone.run(() => {}); 你通常会 scope.$apply

  1. ChangeDetectorRef
  2. 私有(private) chRef:ChangeDetectorRef
  3. chRef.detectChanges();

关于javascript - Angular 2 - 替代 $scope.$apply?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30734646/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com