Another alternative workaround to: "Run Directive after DOM has rendered"

See original article: http://blog.brunoscopelliti.com/run-a-directive-after-the-dom-has-finished-rendering

by gavinfoley

HTML

<script src="http://getfirebug.com/releases/lite/1.2/firebug-lite-compressed.js"></script>
<!doctype html>
<html lang="en" ng-app="myApp">
    
    <head>
        <meta charset="utf-8" />
        <title>My AngularJS App</title>
    </head>
    
    <body ng-controller="stageController">
        <div repeat-hello-world="{{repeat}}"></div>
    </body>

</html>

CSS

</style> <!-- Ugly Hack due to jsFiddle issue: http://goo.gl/BUfGZ --> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.min.js"></script> <style>

JavaScript

'use strict';

// Declare app level module which depends on filters, and services
angular.module('myApp', ['myApp.directives']);

/* Controllers */
function stageController($scope) {
    $scope.repeat = 5;
}

/* Directives */
angular.module('myApp.directives', [])
    .directive('repeatHelloWorld', ['$timeout', function (timer) {
    return {
        link: function (scope, elem, attrs, ctrl) {
            var hello = function () {
                console.info("Repeat number: " + attrs.repeatHelloWorld);
                for (var i = 0; i < attrs.repeatHelloWorld; i++) {
                    console.log("Hello world!");
                }
            }
            //now works - schedule execution of linking function until after DOM has rendered and react to the attribute value changes because of interpolation of the expression {{repeat}}
            attrs.$observe("repeatHelloWorld", hello);
            
            /* No longer required:          
            // timer(hello, 0);
            */
        }
    }
}]);