Search code examples
angularjstwitter-bootstrapmodal-dialogangular-strap

AngularStrap close modal with controller


I'm using AngularStrap with bootstrap.

I have a modal dialog that uses it's own controller. How can I close the modal using this local controller?

I instantiate the controller on a button like this:

<button type="button" 
  class="btn btn-success btn-lg" 
  bs-modal="modal" 
  data-template="user-login-modal.html"
  data-container="body"
  ng-controller="userLoginController"
  >Click here to log in</button>

and the userLoginController has this:

$scope.authenticate = function(){
    this.hide(); // this doesn't work
    }

This is obviously just a demo, I want it to close on successful login, but this is where the code I'd use to close it would go.

I've tried instantiating the modal programmatically (use the $modal service to create the modal) but I haven't been able to figure out how to inject the controller through that method.

If I were to do something like emit an event from the modal using the bs-modal directive, how can I reference the modal to close it?

here's my plnkr: http://plnkr.co/edit/m5gT1HiOl1X9poicWIEi?p=preview


Solution

  • Figured out a good method:

    I moved the ng-controller to the TEMPLATE and instantiate the modal using the provided modal service. I then use a rootscope broad cast to let everyone know that someone successfully logged in.

    new controller code:

    var loginModal = $modal({template:'/template.html', show:false});
    
    $scope.showLogin = function(){
        loginModal.$promise.then(loginModal.show);
    }
    
    $scope.$on("login", function(){
        loginModal.$promise.then(loginModal.hide);
    });
    

    the button just looks like this now:

    <button type="button" 
      class="btn btn-success btn-lg" 
      ng-click="showLogin()"
      >Click here to log in</button>
    

    and my template has the old ng-controller in the first tag.