【问题标题】:How to set input value and updating model value using jquery in Angularjs2?如何在 Angularjs2 中使用 jquery 设置输入值和更新模型值?
【发布时间】:2016-07-20 09:45:51
【问题描述】:

我打算将 angularjs 1 应用程序升级到 angularjs2。 这里的问题是如何在angualrjs2中使用jquery设置输入值和更新模型值。

这是我的代码:

export class AppComponent {
  public user: User = {
    name: 'John',
    address: {
      address1: '11, High Street'
    }
  }
  ngOnInit() {
      console.log("User name ::"+this.user.name)
      console.log('ngOnInit')
      $('#postcode').val('123456');
  }
  public save(form: IUser, isValid: boolean) {
    console.log(form, isValid);
  }
}

plunkr 代码:http://plnkr.co/edit/BGYTpytD7kGMmRODE796

【问题讨论】:

  • 在Angular2中你通常会更新模型,让Angular根据模型更新视图。另请参阅此类似问题stackoverflow.com/questions/38372856/…
  • 谢谢@GünterZöchbauer 是的,我们的应用程序有一些 jquery 依赖项。这是我放在这里的示例场景代码。

标签: javascript jquery angularjs angular


【解决方案1】:

Angular 在内部渲染模型数据,如果必须使用 Jquery,则需要删除 <input> 标记中的数据绑定: 改变

<input type="text" class="form-control" name="postcode"
          [(ngModel)]="user.address.postcode" id="postcode">

<input type="text" class="form-control" name="postcode"
         id="postcode">

查看演示:http://plnkr.co/edit/RVSwYjaLIPE4Uv4s75oD?p=info

另一种更好的方法是改变模型:

public user: User = {
name: 'John',
address: {
  address1: '11, High Street',
  postcode : "N14 46T"   // <--------Add postcode property
  }
}

【讨论】:

  • 谢谢乔伊,但这里我们需要从 jquery 更新值,然后从模型中获取。
  • 当你绑定一个模型时,Jquery是无法改变它的,它违背了Angular内部视图的渲染过程。
猜你喜欢
  • 2017-01-30
  • 2018-06-14
  • 2013-06-11
  • 2011-02-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多