AngularJS:如何知道$compile何时完成?

4

http://plnkr.co/edit/GRVZl35D1cuWz1kzXZfF?p=preview

在自定义的fancybox(也称为lightbox,对话框)中,我使用插值值显示内容。

在服务中,在“打开”fancybox方法中,我这样做:

 open: function(html, $scope) {
        var el = angular.element(html);
        $compile(el)($scope); // how to know when the $compile is over?
        $.fancybox.open(el); // the uncompiled is shown before the compiled
      }

问题在于对话框中的内容在$compile结束之前被加载,因此不到一秒钟后就会刷新对话框内容,并显示相应的值。

这个plunkr可以工作,但我想避免在完全编译之前显示"el":我只想在$compile完成后再显示它

有没有办法知道$compile何时结束,以便我在那之后才在fancybox中显示内容?


你的 Plunker 对我来说运行良好。有什么问题吗? - Davin Tryon
我从fancybox内部的 ng-click 收到了警报... 需要更多解释。 - charlietfl
问题在于编译结束后更新变量所创建的闪烁。 - apelliciari
2个回答

0

我曾经遇到过ngDialog模态框和弹出提供程序的同样问题。我需要根据其高度定位对话框。但是高度取决于已编译的DOM。

最终,我使用$timeout找到了解决方案,就像在这篇文章中描述的那样:http://blog.brunoscopelliti.com/run-a-directive-after-the-dom-has-finished-rendering/

对于您的代码,它将会是这样:

open: function(html, $scope) {
    var el = angular.element(html);
    $compile(el)($scope);
    $timeout(function() {
        $.fancybox.open(el); 
    }, 0);
}

0

你不能将 $scope 注入到服务中,因为没有像单例 $scope 这样的东西。

所以,不要使用 $compile(el)($scope);,而是尝试:

var compiledEl = $compile(el);
 ....

$compile 返回编译后的数据。

顺便提一下

我会为指令提供服务,并将其编译成指令。我认为这是正确的方式。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接