简体   繁体   中英

AngularJS: how to know when the $compile has finished?

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

In the custom fancybox (aka lightbox, a dialog) I show contents with interpolated values.

in the service, in the "open" fancybox method, i do

 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
      }

The problem is that the content in the dialog is loaded before the end of the $compile, so after less than a second i got a refresh of the dialog content with the values.

The plunkr works, but i want to avoid that the "el" is shown before it gets totally compiled: i want to show it only after the $compile has finished his job

Is there a way to know when the $compile it's over so i'll show the content on fancybox only after that?

You can't inject $scope into services, there is nothing like a singleton $scope.

So instead of $compile(el)($scope); try:

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

The $compile returns compiled data.

as a side note

I would provide service to directive and compile it into directive instead. I think it's the right way.

I've had the same problem with the ngDialog modals and popup provider. I needed to position the dialog based on its height. But the height depended on the compiled DOM.

I eventually found a solution using $timeout, like described in that post: http://blog.brunoscopelliti.com/run-a-directive-after-the-dom-has-finished-rendering/

For your code, it would give something like that:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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