angular 2.0 相当于 $scope.$apply [英] angular 2.0 equivalent to $scope.$apply

查看:26
本文介绍了angular 2.0 相当于 $scope.$apply的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试开始使用 angular 2.0,现在我想知道如何在某些外部事件更改数据后启动对视图的更新.

详细地说,我有一个谷歌地图和一个地图上点击事件的处理程序.用户点击地图后,我将点击的纬度和经度存储到控制器上的变量中

this.lat = event.latLng.lat();this.lon = event.latLng.lon();

在视图中我想显示这些值

这是我的位置:{{lat}} 和 {{lon}} </div>

在 angular 1 中,我会简单地将控制器中的赋值包装在对 $scope.$apply() 的调用中.

在angluar 2.0 中更新视图的首选方法是什么?

解决方案

大多数情况下,您无需执行任何操作即可更新视图.zone.js 会为你做一切.

但是如果由于某种原因您想手动触发更改检测(例如,如果您的代码在角度区域之外运行),您可以使用 LifeCycle::tick() 方法来做到这一点.见这个plunker

import {Component, LifeCycle, NgZone} from 'angular2/angular2'@成分({选择器:'我的应用',模板:`<div>你好,世界!!!时间:{{时间}}.

`})出口类应用{时间:数字= 0;构造函数(LC:生命周期,区域:NgZone){zone.runOutsideAngular(() => {setInterval(() => {this.time = Date.now();lc.tick();//注释此行,time"将停止更新}, 1000);})}做检查(){console.log('check', Date.now());}}

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

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

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

解决方案

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

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

这篇关于angular 2.0 相当于 $scope.$apply的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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