角2.0​​相当于$范围。$申请 [英] angular 2.0 equivalent to $scope.$apply

查看:133
本文介绍了角2.0​​相当于$范围。$申请的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想上手角2.0,现在我想知道经过一些外部事件改变了我的数据是如何开始更新到视图。

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.

在细节我有一个谷歌地图,并在地图上点击事件的处理程序。用户点击地图上后,我到变量存储点击的纬度和经度控制器上的

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();

在视图我想显示这些值

<div> this is my spot: {{lat}} and {{lon}} </div>

在角1我只想换到$范围的呼叫控制器的分配。$适用()。

In angular 1 I would simply wrap the assignment in the controller in a call to $scope.$apply().

什么是preferred的方式去更新在angluar 2.0看法?

What is the preferred way to go about updating views in angluar 2.0 ?

推荐答案

大多数情况下,你不需要做任何事情来更新视图。 zone.js 会为你做的一切。

Mostly, you don't need to do anything to update the view. zone.js will do everything for you.

但是,如果由于某种原因,你要手动解雇变化检测(例如,如果你的code上的角区外),可以使用<一个href=\"https://github.com/angular/angular/blob/2.0.0-alpha.44/modules/angular2/src/core/life_cycle/life_cycle.ts#L50\"相对=nofollow> 的LifeCycle ::打勾() 方法来做到这一点。请参见这plunker

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

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());
  }
}

这篇关于角2.0​​相当于$范围。$申请的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆