Run jQuery code after AngularJS completes rendering HTML

前端 未结 4 518
别跟我提以往
别跟我提以往 2020-12-02 08:08

In controller I get some JSON data using $http or $resource services. Then I write this data in $scope and AngularJS updates HTML structure of the page. My problem is that I

4条回答
  •  旧巷少年郎
    2020-12-02 09:02

    I would like to add another answer, since the preceding answers takes it that the code needed to run after the ngRepeat is done is an angular code, which in that case all answers above give a great and simple solution, some more generic than others, and in case its important the digest life cycle stage you can take a look at Ben Nadel's blog about it, with the exception of using $parse instead of $eval.

    But in my experience, as the OP states, it is usually running some jQuery plugins or methods on the finally compiled DOM, which in that case I found that the most simple solution is to create a directive with a setTimeout, since the setTimeout function gets pushed to the end of the queue of the browser, its always right after everything is done in angular, usually ng-repeat which continues after it's parents postLinking function

    angular.module('myApp', [])
    .directive('pluginNameOrWhatever', function() {
      return function(scope, element, attrs) {        
        setTimeout(function doWork(){
          //jquery code and plugins
        }, 0);        
      };
    });
    

    For whoever wondering why not to use $timeout, its that it causes another digest cycle that is completely unnecessary.

    EDIT:

    Thanx to drzaus for the link to how to use $timeout without causing digest http://www.codelord.net/2015/10/14/angular-nitpicking-differences-between-timeout-and-settimeout/

提交回复
热议问题