streetsoldier
streetsoldier

Reputation: 1319

Ember programmatically call controller action from hbs template

I have a defined action on my controller that makes a modal visible. In my hbs template, I am able to create a button and assign it the action. When I do this, I can make the modal appear by clicking the button.

I am trying to show the modal (call the controller action) without having to click anything. Is this possible? I want the modal to pop up based on a conditional on the model automatically.

Upvotes: 0

Views: 486

Answers (2)

Marcell Monteiro Cruz
Marcell Monteiro Cruz

Reputation: 347

Theres a pretty straightforward way to do this, just create a computed alias of the model property that you want

// controller
export default Ember.Controller.extend({
  showModal: Ember.computed.alias('model.showModal')
});

// template
{{#if showModal}}
  <p>Showing modal</p>
{{/if}}

that's it

working example: https://ember-twiddle.com/3e86c841e9d7ea54d4febd74b5463fb8?openFiles=controllers.application.js%2C

Upvotes: 1

patocallaghan
patocallaghan

Reputation: 305

You could create a component, add the button to the component and then pass the model and action into the component.

Then in the component's init lifecycle hook, do your model conditional check and call the passed in action if it's 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')();
        }
    }
});

From my knowledge, there's no lifecycle hook in a controller which fires every time you visit a specific page. Adding your check to a component guarantees your check will fire each time you visit the page as it will always render the button component.

Upvotes: 0

Related Questions