Search code examples
javascriptjqueryangularjstwitter-bootstrapangular-controller

How to activate new Angular controller after bootstrapping


I have an Angular application that uses automatic bootstrapping with the ng-app attribute. I then, later, add a DOM subtree in a Bootstrap modal dialog from an HTML template, like so:

<!DOCTYPE html>
<html ng-app="Foo">
 <head>
  <link href="lib/bootstrap/css/bootstrap.min.css"  rel="stylesheet" media="screen" />
 </head>

 <body>
  <a href="template.html" data-toggle="modal" data-target="#modal">Modal</a>

  <div class="modal fade" id="modal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
      <div class="modal-content">
      </div>
    </div>
  </div>

  <script src="lib/jquery/jquery.js"></script>
  <script src="lib/bootstrap/js/bootstrap.js"></script>
  <script src="lib/angular.js/angular.js"></script>
 </body>
</html>

Now, in the template, I have a div with an ng-controller attribute to bind a registered controller to it, like so:

<div ng-controller="ViewModalController">
</div>

The controller is regularly registered within the application.

However, the controller is not bound after loading the modal, as I guess because the ng-controller div was not available during bootstrapping.

How can I have Angular pick it up upon loading?


Solution

  • Yes, you are right. That is not working because it was not there at the time of Bootstrap and you are loading the new template using jQuery for which Angular is not compiling the template.

    To make things work, you should compile the newly added HTML like so (do this in one of your controller and inject $compile):

    $("#modal").on("shown.bs.modal", function() {
        var $modal = angular.element(document.getElementById('modal'));
    
        $compile($modal.contents())($scope);
    });
    

    See the working example here: https://plnkr.co/edit/zASHzGwOLxku12Ae5hnP?p=preview

    Important

    The remote option you are using to load the template has been deprecated and is removed in Bootstrap 4. Better not to use it.

    Also, Angular's UI team has written the native Angular code for Bootstrap's Javascript features so you don't need the jQuery and the bootstrap.js file when using with Angular.

    Checkout http://angular-ui.github.io/bootstrap/#/modal