Wednesday, September 24, 2014

AngularJS: evaluating when the angular loading done

Here is the code
    DCTApp.directive('caatInitialized',
    ['$rootScope',
        function($rootScope) {
            return {
                restrict: 'A',
                link: function($scope) {
                    var to;
                    var listener = $scope.$watch(function() {
                        clearTimeout(to);
                        to = setTimeout(function () {
                            console.log('detail Initialized');
                            listener();
                            $rootScope.$broadcast('detailInitialized');
                        }, 50);
                    });
                }
            };
        }]);

Listening (I am calculating the height of the Kendo UI Grid Content here)
        $scope.$on('detailInitialized', function () {
            if (typeof _navParam !== 'undefined' && _navParam !== '') {
                $('.sidebar').show();                
            }
            $('#MemberGrid .k-grid-content').height($('.contentDetail').height() - $('#MemberGrid .k-grid-pager').outerHeight() - $('#MemberGrid .k-grid-header').outerHeight());
            
        });

Then add as an attribute to the element monitoring.
And a note from original post:
It works by assuming that the application is initialised when there are no more $digest cycles. $watch is called every digest cycle and so a timer is started (setTimeout not $timeout so a new digest cycle is not triggered). If a digest cycle does not occur within the timeout then the application is assumed to have initialised.
It is obviously not as accurate as satchmoruns solution (as it is possible a digest cycle takes longer than the timeout) but my solution doesn't need you to keep track of the modules which makes it that much easier to manage (particularly for larger projects). Anyway, seems to be accurate enough for my requirements. Hope it helps.

No comments:

Post a Comment