0

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);
  });
6
  • 2
    Why are you using jquery code in an Angular controller? Just add an ng-click to the label. Commented Jan 30, 2018 at 15:06
  • Suppose I have no access to the HTML code, only to JS, the generated labels number (I need to attach the click to all labels) is not know in advance. Commented Jan 30, 2018 at 15:18
  • Here, I made a Plunker, for you to try and adjust how you need it. Commented Jan 30, 2018 at 15:24
  • @Serge for a dynamic approach you would need to $compile your html instead (for ng-click to work), where unknown functions should be added with a bracket notation Commented Jan 30, 2018 at 15:28
  • 1
    @Serge ah yes, good old nested modals Commented Jan 30, 2018 at 15:56

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

A bit modified CodePen example
1
$uibModalInstance.rendered.then(function(){
  // run your code here and you are fine.
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.