2017-01-10 55 views
1

使用Aurelia,我正在寻找类似于Angular 1的行为,在那里我可以使用ng-show的功能。如: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> 

如果初始值是opt1,显示div,但当选择更改时不显示/隐藏。我能得到这个工作的唯一途径就是通过这样做:

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

这不是在这种情况糟糕,但我希望做这样的事情,我觉得会在JS的函数,而更好地工作比标记:提前

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

谢谢!

回答

7

的一种方法是使你的功能一个getter:

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 –