Ember 以编程方式从 hbs 模板调用控制器操作
Ember programmatically call controller action from hbs template
我在我的控制器上定义了一个动作,它使模态可见。在我的
hbs 模板,我能够创建一个按钮并为其分配操作。当我这样做时,我可以通过单击按钮使模态出现。
我正在尝试显示模式(调用控制器操作)而无需单击任何内容。这可能吗?我希望根据模型的条件自动弹出模态。
您可以创建一个组件,将按钮添加到该组件,然后将模型和操作传递到该组件。
然后在组件的 init
生命周期挂钩中,执行模型条件检查,如果它是 true
,则调用传入的操作。
// some-template.hbs
{{component-with-button
model=model
openModal=(action 'openModal')
}}
// components/component-with-button.js
Component.extend({
init() {
this._super(...arguments);
if (this.get('model.conditionalCheck')) {
this.get('openModal')();
}
}
});
据我所知,控制器中没有生命周期挂钩,它会在您每次访问特定页面时触发。将检查添加到组件可确保每次访问页面时都会触发检查,因为它始终会呈现按钮组件。
有一种非常简单的方法可以做到这一点,
只需创建您想要的模型 属性 的计算别名
// controller
export default Ember.Controller.extend({
showModal: Ember.computed.alias('model.showModal')
});
// template
{{#if showModal}}
<p>Showing modal</p>
{{/if}}
就是这样
工作示例:https://ember-twiddle.com/3e86c841e9d7ea54d4febd74b5463fb8?openFiles=controllers.application.js%2C
我在我的控制器上定义了一个动作,它使模态可见。在我的 hbs 模板,我能够创建一个按钮并为其分配操作。当我这样做时,我可以通过单击按钮使模态出现。
我正在尝试显示模式(调用控制器操作)而无需单击任何内容。这可能吗?我希望根据模型的条件自动弹出模态。
您可以创建一个组件,将按钮添加到该组件,然后将模型和操作传递到该组件。
然后在组件的 init
生命周期挂钩中,执行模型条件检查,如果它是 true
,则调用传入的操作。
// some-template.hbs
{{component-with-button
model=model
openModal=(action 'openModal')
}}
// components/component-with-button.js
Component.extend({
init() {
this._super(...arguments);
if (this.get('model.conditionalCheck')) {
this.get('openModal')();
}
}
});
据我所知,控制器中没有生命周期挂钩,它会在您每次访问特定页面时触发。将检查添加到组件可确保每次访问页面时都会触发检查,因为它始终会呈现按钮组件。
有一种非常简单的方法可以做到这一点, 只需创建您想要的模型 属性 的计算别名
// controller
export default Ember.Controller.extend({
showModal: Ember.computed.alias('model.showModal')
});
// template
{{#if showModal}}
<p>Showing modal</p>
{{/if}}
就是这样
工作示例:https://ember-twiddle.com/3e86c841e9d7ea54d4febd74b5463fb8?openFiles=controllers.application.js%2C