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

前端 未结 6 657
余生分开走
余生分开走 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: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
    });
    

提交回复
热议问题