简体   繁体   English

Angular模态窗口($ uibModalInstance)打开后如何运行代码?

[英]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. 以此CodePen为基础。 Suppose an (demo) need to alert the label content on click on all the labels in the modal window: 假设(演示)需要在模式窗口中单击所有标签时提醒标签内容:

在此处输入图片说明

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);
  });

Your code doesn't have any effect because when it executes, the template is not a part of the DOM yet. 您的代码没有任何作用,因为执行时,该模板尚未成为DOM的一部分。 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. 您会看到它返回0。因此,您所要做的就是等到模板加载的那一刻。 There is one common trick in Angular, which helps in such situations: put your code in a $timeout service, like this: Angular中有一个常见的技巧,在这种情况下会有所帮助:将代码放入$ timeout服务中,如下所示:

$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. 超时会将代码放在当前执行管道的最后,此时,弹出模板将位于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. 但这当然是一个肮脏的技巧:)如果您需要编写一些jQuery代码,则采用更广角的方式是编写一个单独的指令并将其应用于模板中的各个元素。 And don't forget about the huge variety of native directives, such as "ng-click" and etc. 并且不要忘记各种各样的本地指令,例如“ ng-click”等。

$uibModalInstance.rendered.then(function(){
  // run your code here and you are fine.
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM