Aurelia - 根据功能结果隐藏/显示Div

时间:2017-01-10 05:59:09

标签: javascript aurelia

使用Aurelia,我正在寻找与Angular 1类似的行为,我可以使用ng-show的函数。如:

<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>

提前致谢!

1 个答案:

答案 0 :(得分: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');
    }
}