How to run a function after Angularjs renders content in the template?

Asked

Viewed 5,596 times

0

I would like to call a function after Angularjs renders the content in the template, just as it removes the display:none when using the ng-cloak.

function executaAposRenderizar(){...}
app.controller('lista', ['$scope', function($scope) {
    $scope.itens = [...]
    // executaAposRenderizar();
}])

How to call a function after Angularjs has printed the content in the template?

2 answers

1


I was able to solve it this way:

app.directive('executarAposRenderizar', function ($timeout) {
    return {
        restrict: 'A',
        link: function (scope, element, attr) {
            if (scope.$last === true) {
                scope.$evalAsync(attr.executarAposRenderizar);
            }
        }
    }
});

app.controller('lista', ['$scope', function($scope) {
    $scope.itens = [...]
    $scope.alerta = function(){console.log('sucesso');};
}])

HTML:

<ul ng-app="app" ng-controller="lista">
    <li ng-repeat="item in itens" executar-apos-renderizar="alerta()">{{item}}</li>
</ul>

After executing the last loop item is called the alerta() of $scope through the executar-apos-renderizar.

References:

0

Try to use the timeout$ to place the function in the browser’s events list.

function executaAposRenderizar(){...}
app.controller('lista', ['$scope','$timeout', function($scope,$timeout) {
    $scope.itens = [...]
    $timeout(executaAposRenderizar, 0);

}])

Browser other questions tagged

You are not signed in. Login or sign up in order to post.