【问题标题】:How to run code after an Angular modal window ($uibModalInstance) opens?如何在 Angular 模态窗口 ($uibModalInstance) 打开后运行代码?
【发布时间】:2018-01-30 15:05:27
【问题描述】:

我需要在模态窗口中响应某些事件。

以此CodePen为基础。 假设一个(演示)需要在模态窗口中点击所有标签时提醒标签内容:

我在模态控制器中的代码无效

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

【问题讨论】:

  • 为什么在 Angular 控制器中使用 jquery 代码?只需在标签上添加一个 ng-click。
  • 假设我无法访问HTML代码,只有JS,生成的标签编号(我需要将点击附加到所有标签)是事先不知道的。
  • 这里,我做了一个Plunker,供你尝试调整你需要的方式。
  • @Serge 对于动态方法,您需要 $compile 您的 html 代替(ng-click 工作),其中未知功能应添加 bracket notation
  • @Serge 是的,好的旧嵌套模态

标签: jquery angularjs angular-ui-bootstrap angular-ui-modal


【解决方案1】:

您的代码没有任何效果,因为当它执行时,模板还不是 DOM 的一部分。如果把这行代码放在控制器里:

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

您可以看到它返回 0。因此,您只需等到模板加载的那一刻。 Angular 中有一个常见的技巧,在这种情况下会有所帮助:将代码放入 $timeout 服务中,如下所示:

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

超时会将代码置于当前执行管道的最后,此时弹出模板将位于 DOM 中。

但这当然是一个肮脏的 hack :) 如果您需要编写一些 jQuery 代码,更多的 Angular 方法是编写一个单独的指令并将其应用于模板中的相应元素。并且不要忘记种类繁多的原生指令,例如“ng-click”等。

【讨论】:

【解决方案2】:
$uibModalInstance.rendered.then(function(){
  // run your code here and you are fine.
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-21
    • 2020-04-18
    • 2017-08-24
    • 1970-01-01
    • 2023-03-02
    • 2012-10-03
    • 2016-09-17
    • 1970-01-01
    相关资源
    最近更新 更多