srinivas
srinivas

Reputation: 5108

Unable to trigger modal-dialog show in Meteor template

I have a modal dialog in my template. This dialog needs to be triggered from the code programatically. So I need to show the modal through javascript, as I cannot have a data-toggle button to launch the modal-dialog.

The modal was working with bootstrap but with bootstrap-3 its not showing up, even though I can show it from the console directly. the problem here is how can I execute javascript post the template render, to launch the modal-dialog.

There is a Template.rendered/created function which is called, and inside this this.autorun(runFunc) is supposed to run the code to update the DOM element. This is called correctly, but I still cannot trigger the modal to show-up.

Template.createDialog.created = function() {
console.log("teamplate created");

this.autorun(function(){
    $('#myModal').modal('show');    
  });
};

Update: This works:

Template.createDialog.rendered = function() {
console.log("teamplate created");

this.autorun(function(){
    $('#myModal').modal('show');    
  });
};

Using the rendered function, I am able to trigger the modal to show up. But the problem is that rendered and created both are only called once. And I need a way to trigger the modal dialog consistently if a condition is reached.

This bootstrap modal dialog with meteor is turning out to be painful and hacky. Is it not possible to show/hide modal using some class parameters?

Upvotes: 0

Views: 1289

Answers (1)

richsilv
richsilv

Reputation: 8013

Modals can be tricky to get right in Meteor for exactly the reasons you've discovered. I don't use Bootstrap, but the basic principle is that you need to trigger the modal programatically so that you can run the relevant framework code once you know the html has been rendered but still retain reactivity (this is certainly the case with Foundation and Semantic-UI modals) .

In your use case (which appears to be a single modal), this shouldn't be too much of a problem. Set a reactive variable modalVisible (a Session variable or similar), and use that to show or hide the modal as required.

this.autorun(function(c) {
    if (Session.get('modalVisible')) {
        $('#myModal').modal('show'); 
    } else {
        $('#myModal').modal('hide');
    }
});

If you put all of that in the rendered callback then it will only try to show the modal once it's been added to the DOM (without which you'll get an error and the computation will stop running, breaking reactivity). Note that you shouldn't make rendering of the template dependent on a reactive variable - it should always be rendered but only visible based on the value of the modalVisible Session variable.

Apologies if this is too simple for your use case - if so I would recommend investigating the several packages on Atmosphere for Bootstrap modals as others will almost certainly have faced the same problem.

Upvotes: 1

Related Questions