javascriptember.jsember-bootstrap

Trigger Bootstrap modal thats in a component from another template


I am using ember-bootstrap and their modal component to create a modal on a template. Currently the modal component and the button to trigger it are on the same template, however I want to move the modal to a component so I can keep the template code clean.

This works

//application/template.hbs
{{#bs-button onClick=(action (mut modal1) true)}}Open Modal{{/bs-button}}

{{#bs-modal-simple open=modal1 title="Simple Dialog" size="sm" onHidden=(action (mut modal1) false)}}
  Hi there
{{/bs-modal-simple}}

This doesn't work

//application/template.hbs
{{#bs-button onClick=(action (mut modal1) true)}}Open Modal{{/bs-button}}
{{my-modal}}

//components/my-modal/template.hbs
{{#bs-modal-simple open=modal1 title="Simple Dialog" size="sm" onHidden=(action (mut modal1) false)}}
  Hi there
{{/bs-modal-simple}}

How could I get it so the modal is triggered from the applications template?


Solution

  • In your code, my-modal component is unaware of modal1 boolean you change in application.hbs upon button click to display the modal dialog. What you need to do is passing modal1 attribute to my-modal. Check out the twiddle. By passing the boolean attribute to my-modal component you are now modifying the same boolean both on application.hbs and my-modal.hbs. (Note that, I updated the twiddle to respect Data Down Action Up principle; so that modal1 is only updated by application and not my-modal. modal1 attribute is now only readonly for my-modal).

    However; when trying to display modal on a big project and to trigger modal dialog not only from application.hbs but from anywhere in the application; what I do is typically creating a service and delegating visibility management of modal dialog to that service. You should consider such an approach if you are to develop something bigger.