如何将视图中的更改绑定回控制器?

时间:2016-05-26 03:07:54

标签: angular ionic2

我试图了解ionic2 / angular2,并且已经陷入了如何将视图中的更改绑定回控制器的问题。

在下面的代码段中,我设置了两个模态选择框,但都没有将模型更改传播回控制器 - 它会重新加载默认值。我怎样才能传回变量?

HTML:

  <ion-select [(ngModel)]="base" (ngModelChange)="loadCurrencyExchange()">
    <ion-option *ngFor="let b of supportedCurrencies" value="{{b}}">
      {{b}}
    </ion-option>
  </ion-select> to

  <ion-select [(ngModel)]="symbols" (ngModelChange)="loadCurrencyExchange()" multiple="true">
    <ion-option *ngFor="let s of supportedCurrencies" value="{{s}}">
      {{s}}
    </ion-option>
  </ion-select>

JS(根据答案更新):

 export class HomePage {
    public currenciesLoaded: any;
    public supportedCurrencies: string[];
    @Output() public exchangeRates: any;
    public dataLoaded: boolean;

    @Input() base: string = 'USD';
    @Input() symbols: string[] = ['EUR','RUB'];

    constructor(public CurrencyService: CurrencyService) {
        var base: string = this.base;
        var symbols: string[] = this.symbols;
        this.loadCurrencyList();
        this.loadCurrencyExchange();
    }

    loadCurrencyList(){
        this.supportedCurrencies =this.CurrencyService.loadCurrencySymbols();
    }

    loadCurrencyExchange(){
        this.CurrencyService.loadCurrencies(this.base, this.symbols)
            .then(data => {
                console.log(this.base + ' to ' + this.symbols.join(','));
                this.exchangeRates = data;
                this.currenciesLoaded = Object.keys(data.rates);
                this.dataLoaded = true;
            })
    }
}

1 个答案:

答案 0 :(得分:1)

修改

当你有多个选择时,有一些错误的行为;我发现隔离模型的方法是将它们嵌入ion-item;检查this plunker是否有工作版本:不需要@Input@Output装饰器。

  <ion-item>
    <ion-select name="select1" [(ngModel)]="base" (ngModelChange)="loadCurrencyExchange()">
      <ion-option *ngFor="let b of supportedCurrencies" value="{{b}}">
        {{b}}
      </ion-option>
    </ion-select>
  </ion-item>

  <ion-item>
    <ion-select name="select2" [(ngModel)]="symbols" (ngModelChange)="loadCurrencyExchange()" multiple="true">
      <ion-option *ngFor="let s of supportedCurrencies" value="{{s}}">
        {{s}}
      </ion-option>
    </ion-select>
  </ion-item>