2017-03-28 105 views
2

鉴于以下角2代码中查找当前位置,并转换到人类可读串 - >结合于输入元件:角2犯规更新视图

HTML tempalte:

<input name="myAddr" [(ngModel)]="form.address" type="text"> 
<button (click)="findMyLocation()" class="ui location right blue icon button"> 
    <i class="marker icon"></i> 
</button> 

角2代码:

form: { 
    volume: number, 
    thickness: number, 
    density: number, 
    address: string 
    } = { address: '', volume: 0, thickness: 100, density: 300 }; 

findMyLocation(){ 
    $('.location').addClass('loading'); 
    navigator.geolocation.getCurrentPosition(position => { 
     this.geocoder.geocode({location: { lat: position.coords.latitude, lng: position.coords.longitude }}, (results, status)=>{ 
     if(status == 'OK') 
      if(results[0]){ 
      $('.location').removeClass('loading'); 
      console.log('Addr: ' + results[0].formatted_address); 
      this.form.address = results[0].formatted_address; 
      } 
     }) 
    }, fail => { 
     console.log(fail); 
    }); 
    } 

然而,当我点击按钮,位置(纬度,经度)被转换为可读胡马尔ADRESS,我可以看到输出到控制台。但输入元素不会改变。如果我再次点击按钮,元素就会得到更新,因为它应该是。 这是怎么回事? Screen-1, ClcikedScreen-2, clicked twice

+0

据我所知角不看在变化对象属性,但只有对象本身(其引用)。如果用新对象替换“表单”,则会看到视图中的更改。 – abhishekkannojia

+0

刚刚测试过,声明其他单个字符串变量也可以工作:(它工作,如果我点击两次按钮,但这是意想不到的行为。 –

回答

2

Bacause navigator.geolocation.getCurrentPosition是异步函数,您必须使用ngZone.run让角度重新渲染模型。

this.ngZone.run(function() { 
    this.form.address = results[0].formatted_address; 
};) 

注意:你必须在你的构造导入NgZoneinject它。

UPD:有两种方式,因为我知道:

  • ngZone.run()
  • ChangeDetectorRef.detectChanges()
+0

感谢!工作就像魅力所以,每个第三方库的asyc函数应该运行在ngZone? –

+0

@EvghenyKalkutin我已经更新了你的评论的答案,因为对于我来说,我总是使用第一个相当于$ scope的。$ apply()经常用在angular1.x中 – Pengyy

+0

谢谢,Pengyy! –