2017-01-10 13 views
1

Aureliaを使用して、私はng-showの関数を使用できるAngular 1と​​同様の動作を探しています。以下のような:ここでAurelia - 関数の結果に基づいてdivを表示/非表示

<div ng-show='isShown()'></div> 

は私がやろうとしています何の例です:

app.js

export class App { 
    this.options = ['opt1', 'opt2', 'opt3', 'opt4, 'opt5']; 
    this.current = ""; 
    isShown() { 
     return (this.current === 'opt1'); 
    } 
} 

app.html

<select value.bind="current"> 
    <option repeat.for="opt of options" model.bind="opt">${opt}</option> 
</select> 

<div if.bind="isShown()">...</div> 

初期値がの場合210の場合、divが表示されますが、選択が変わると表示/非表示はしません。私はこの仕事を得ることができる唯一の方法は、これを行うことである。

<div if.bind="current === 'opt1'"></div> 

これは、このような状況では悪いことではありませんが、私は、私はむしろ、JS関数とのより良い仕事と感じ、このような何かを期待していましたマークアップよりも:

<div if.bind="current === 'opt1' || current === 'opt2' || current === 'opt3'"></div> 

ありがとうございます!

答えて

7

一つの方法は、あなたの関数ゲッターを作ることです。

get isShown() { 
    return (this.current === 'opt1'); 
} 

と:

<div if.bind="isShown">Show/Hide</div> 

が、あなたがcomputedFromを使用できることを避けるために、チェックし汚れになりますこのよう:

import { computedFrom } from 'aurelia-framework'; 

export class App { 

    constructor() { 
     this.options = ['opt1', 'opt2', 'opt3', 'opt4', 'opt5']; 
     this.current = ''; 
    } 

    @computedFrom('current') 
    get isShown() { 
     return (this.current === 'opt1'); 
    } 

} 

@observable

import { observable } from 'aurelia-framework'; 

export class App { 

    isShown = false; 
    @observable current = ''; 

    currentChanged(newValue, oldValue) { 
     this.isShown = (newValue === 'opt1'); 
    } 

} 

そして、あなたはまた、使用することができBindingEngineは:

import { BindingEngine, inject } from 'aurelia-framework'; 

@inject(BindingEngine) 
export class App { 

    isShown = false; 
    current = ''; 
    options = ['opt1', 'opt2', 'opt3', 'opt4', 'opt5']; 

    constructor(bindingEngine) { 
     this.bindingEngine = bindingEngine; 

     this.bindingEngine 
      .propertyObserver(this, 'current') 
      .subscribe(this.currentChanged.bind(this)); 
    } 

    currentChanged(newValue, oldValue) { 
     this.isShown = (newValue === 'opt1'); 
    } 
} 
+0

私は素晴らしい仕事@observableアプローチ –

+0

を追加しました! ES2015を使用している場合、ここにいくつかの変更が加えられます:http://aurelia.io/hub.html#/doc/article/aurelia/binding/latest/binding-computed-properties/1 –

関連する問題