How to trigger a method when Angular is done adding scope updates to the DOM?

前端 未结 6 644
余生分开走
余生分开走 2020-11-29 21:50

I am looking for a way to execute code when after I add changes to a $scope variable, in this case $scope.results. I need to do this in order to call some legacy code that r

相关标签:
6条回答
  • 2020-11-29 22:07

    interval works for me,for example:

    interval = $interval(function() {
        if ($("#target").children().length === 0) {
            return;
        }
        doSomething();
        $interval.cancel(interval);
    }, 0);
    
    0 讨论(0)
  • 2020-11-29 22:08

    Using timeout is not the correct way to do this. Use a directive to add/manipulate the DOM. If you do use timeout make sure to use $timeout which is hooked into Angular (for example returns a promise).

    0 讨论(0)
  • 2020-11-29 22:09

    I forked your fiddle. http://jsfiddle.net/xGCmp/7/

    I added a directive called emit-when. It takes two parameters. The event to be emitted and the condition that has to be met for the event to be emitted. This works because when the link function is executed in the directive, we know that the element has been rendered in the DOM. My solution is to emit an event when the last item in the ng-repeat has been rendered.

    If we had an all Angular solution, I would not recommend doing this. It is kind of hacky. But, it might be an okey solution for handling the type of legacy code that you mention.

    var myApp = angular.module('myApp', []);
    
    myApp.controller("myController", ['$scope', function($scope){
        var resultsToLoad = [
            {id: 1, name: "one"},
            {id: 2, name: "two"},
            {id: 3, name: "three"}
        ];
    
        function doneAddingToDom() {
            console.log(document.getElementById('renderedList').children.length);
        }
    
        $scope.results = [];
    
        $scope.loadResults = function(){
            $scope.results = resultsToLoad;
            // If run doneAddingToDom here, we will find 0 list elements in the DOM. Check console.
            doneAddingToDom();
        }
    
        // If we run on doneAddingToDom here, we will find 3 list elements in the DOM.
        $scope.$on('allRendered', doneAddingToDom);
    }]);
    
    myApp.directive("emitWhen", function(){
        return {
            restrict: 'A',
            link: function(scope, element, attrs) {
                var params = scope.$eval(attrs.emitWhen),
                    event = params.event,
                    condition = params.condition;
                if(condition){
                    scope.$emit(event);
                }
            }
        }
    });
    
    angular.bootstrap(document, ['myApp']);
    
    0 讨论(0)
  • 2020-11-29 22:09

    I had a custom directive and I needed the resulting height() property of the element inside my directive which meant I needed to read it after angular had run the entire $digest and the browser had flowed out the layout.

    In the link function of my directive;

    This didn't work reliably, not nearly late enough;

    scope.$watch(function() {}); 
    

    This was still not quite late enough;

    scope.$evalAsync(function() {});
    

    The following seemed to work (even with 0ms on Chrome) where curiously even ẁindow.setTimeout() with scope.$apply() did not;

    $timeout(function() {}, 0);
    

    Flicker was a concern though, so in the end I resorted to using requestAnimationFrame() with fallback to $timeout inside my directive (with appropriate vendor prefixes as appropriate). Simplified, this essentially looks like;

    scope.$watch("someBoundPropertyIexpectWillAlterLayout", function(n,o) {
        $window.requestAnimationFrame(function() {
            scope.$apply(function() {
                scope.height = element.height(); // OK, this seems to be accurate for the layout
            });
        });
    });
    

    Then of course I can just use a;

    scope.$watch("height", function() {
        // Adjust view model based on new layout metrics
    });
    
    0 讨论(0)
  • 2020-11-29 22:12

    If you're like me, you'll notice that in many instances $timeout with a wait of 0 runs well before the DOM is truly stable and completely static. When I want the DOM to be stable, I want it to be stable gosh dang it. And so the solution I've come across is to set a watcher on the element (or as in the example below the entire document), for the "DOMSubtreeModified" event. Once I've waited 500 milliseconds and there have been no DOM changes, I broadcast an event like "domRendered".

    IE:

       //todo: Inject $rootScope and $window, 
    
    
       //Every call to $window.setTimeout will use this function
       var broadcast = function () {};
    
       if (document.addEventListener) {
    
           document.addEventListener("DOMSubtreeModified", function (e) {
               //If less than 500 milliseconds have passed, the previous broadcast will be cleared. 
               clearTimeout(broadcast)
               broadcast = $window.setTimeout(function () {
                   //This will only fire after 500 ms have passed with no changes
                   $rootScope.$broadcast('domRendered')
               }, 500)
    
           });
    
       //IE stupidity
       } else {
           document.attachEvent("DOMSubtreeModified", function (e) {
    
               clearTimeout(broadcast)
               broadcast = $window.setTimeout(function () {
                   $rootScope.$broadcast('domRendered')
               }, 500)
    
           });
       }
    

    This event can be hooked into, like all broadcasts, like so:

    $rootScope.$on("domRendered", function(){
       //do something
    })
    
    0 讨论(0)
  • 2020-11-29 22:20

    The $evalAsync queue is used to schedule work which needs to occur outside of current stack frame, but before the browser's view render. -- http://docs.angularjs.org/guide/concepts#runtime

    Okay, so what's a "stack frame"? A Github comment reveals more:

    if you enqueue from a controller then it will be before, but if you enqueue from directive then it will be after. -- https://github.com/angular/angular.js/issues/734#issuecomment-3675158

    Above, Misko is discussing when code that is queued for execution by $evalAsync is run, in relation to when the DOM is updated by Angular. I suggest reading the two Github comments before as well, to get the full context.

    So if code is queued using $evalAsync from a directive, it should run after the DOM has been manipulated by Angular, but before the browser renders. If you need to run something after the browser renders, or after a controller updates a model, use $timeout(..., 0);

    See also https://stackoverflow.com/a/13619324/215945, which also has an example fiddle that uses $evalAsync().

    0 讨论(0)
提交回复
热议问题