jqueryangularjsangular-ui-bootstrapangular-ui-modal

How to run code after an Angular modal window ($uibModalInstance) opens?


I need to respond at some events in a modal window.

Take this CodePen as base. Suppose an (demo) need to alert the label content on click on all the labels in the modal window:

enter image description here

my code in the modal's controller has no effect

angular.module('ui.bootstrap.demo')
  .controller('ModalInstanceCtrl',
              function ($scope, $uibModalInstance) {
  $('label').click(function(e){
    console.log(e);
  });

Solution

  • Your code doesn't have any effect because when it executes, the template is not a part of the DOM yet. If you put this line of code in the controller:

    console.log($('label').length);
    

    you can see that it returns 0. So, all you need is to wait until the moment the template loads. There is one common trick in Angular, which helps in such situations: put your code in a $timeout service, like this:

    $timeout(function() {
      $('label').on('click', function(e){
        console.log(e);
      });
    });
    

    Timeout will put the code at the very end of your current execution pipeline, and at that moment the popup template will be in DOM.

    But this is a dirty hack of course :) More Angular way, in case you need to write some jQuery code, is to write a separate directive and apply it to the respective elements in your template. And don't forget about the huge variety of native directives, such as "ng-click" and etc.