按钮:在Ember.js中按ID更改值

时间:2017-01-30 14:45:29

标签: ember.js

我正在尝试在{{#each}}<button>...</button>{{/each}}块中设置一组按钮,并通过模型的ID获取目标值...

假设有一个带模型和动作的控制器:

export default Ember.Component.extend({

    Texts: [
        {id: "1", name: "One", sample: "Hello!"},
        {id: "2", name: "Two", sample: "Hello! Hello!"},
        {id: "3", name: "Three", sample: "Hello! Hello! Hello! "},
    ],

    theText: "Test",

    actions: {
        setText: function(id) {
            var theText= this.get('Texts.sample', id);
            this.set('theText');
            console.log(theText);
        }

});

,这在模板中:

{{#each Texts as |Text|}}
    <button {{action "setText" Text.id}}>{{Text.name}}</button>
{{/each}}

<span>{{theText}}</span>

......这是我的想法,但我得到的只是 undefined ......

1 个答案:

答案 0 :(得分:1)

  1. 在init方法中定义数组属性。
  2. 使用findBy方法获取匹配的ID行。
  3.     export default Ember.Component.extend({
            Texts: undefined,
            theText: "Test",
            init() {
                this._super(...arguments);
                this.set('Texts', [
                    { id: "1", name: "One", sample: "Hello!" },
                    { id: "2", name: "Two", sample: "Hello! Hello!" },
                    { id: "3", name: "Three", sample: "Hello! Hello! Hello! " },
                ]);
            },
            actions: {
                setText: function(id) {
                    let result = this.get('Texts').findBy('id', id);
                    this.set('theText', result.sample);
                    console.log(result);
                }
            }
        });