Javascript angular 2.0 相当于 $scope.$apply
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33174146/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
angular 2.0 equivalent to $scope.$apply
提问by Tobias Gassmann
I am trying to get started with angular 2.0, now I was wondering how I can initiate an update to the view after some external event changed data.
我正在尝试开始使用 angular 2.0,现在我想知道如何在某些外部事件更改数据后启动对视图的更新。
In details I have a google map and a handler for a click-event on the map. After the user clicks on the map I store latitude and longitude of the click in to variables on the controller
详细地说,我有一个谷歌地图和一个地图上点击事件的处理程序。用户点击地图后,我将点击的纬度和经度存储到控制器上的变量中
this.lat = event.latLng.lat();
this.lon = event.latLng.lon();
In the view I want to display these values
在视图中我想显示这些值
<div> this is my spot: {{lat}} and {{lon}} </div>
In angular 1 I would simply wrap the assignment in the controller in a call to $scope.$apply().
在 angular 1 中,我会简单地将控制器中的赋值包装在对 $scope.$apply() 的调用中。
What is the preferred way to go about updating views in angluar 2.0 ?
在 angluar 2.0 中更新视图的首选方法是什么?
采纳答案by alexpods
Mostly, you don't need to do anything to update the view. zone.jswill do everything for you.
大多数情况下,您无需执行任何操作即可更新视图。zone.js会为你做一切。
But if for some reason you want to fire change detection manually (for example if your code is running outside of an angular zone) you can use LifeCycle::tick()
method to do it. See this plunker
但是,如果由于某种原因您想手动触发更改检测(例如,如果您的代码在角度区域之外运行),您可以使用LifeCycle::tick()
method 来做到这一点。看到这个 plunker
import {Component, LifeCycle, NgZone} from 'angular2/angular2'
@Component({
selector: 'my-app',
template: `
<div>
Hello world!!! Time: {{ time }}.
</div>
`
})
export class App {
time: number = 0;
constructor(lc: LifeCycle, zone: NgZone) {
zone.runOutsideAngular(() => {
setInterval(() => {
this.time = Date.now();
lc.tick(); // comment this line and "time" will stop updating
}, 1000);
})
}
doCheck() {
console.log('check', Date.now());
}
}
回答by Hari Das
Try to import ChangeDetectorReffrom angular core as follow
尝试从 angular core导入ChangeDetectorRef如下
import {Component, ChangeDetectorRef} from '@angular/core';
in constructor
在构造函数中
constructor(private chRef: ChangeDetectorRef){
chRef.detectChanges(); //Whenever you need to force update view
}
回答by Aishwat Singh
setTimeout(function(){
//whatever u want here
},0)
ref : http://blog.mgechev.com/2015/04/06/angular2-first-impressions/
参考:http: //blog.mgechev.com/2015/04/06/angular2-first-impressions/