Ike
Ike

Reputation: 1224

How to trigger an event after AngularJS model has been bound to view

When I assign a new value to the model of AngularJS I notice there is a little delay before the page gets refreshed with the data of the new model. This happens especially if the model is a very fat one.

I am thinking of showing a mask div while AngularJS is applying the new model to view. Is there a way to do this ?

Basically I would like to get notified when AngularJS finishes applying the new model to the HTML view.

Thanks

Upvotes: 1

Views: 3029

Answers (1)

Dan
Dan

Reputation: 63139

Assuming you are doing that work inside of a controller, one option would be using the ng-show directive on your masking element like:

<div ng-controller="someCtrl">
    <div ng-show="loading">I'm a mask</div>
</div>

And in your app:

myApp.controller('someCtrl',function($scope,$timeout){
    function doHeavyLoading(){
        // do the loading here
        $scope.loading = false;
    }
    $scope.loading = true;
    $timeout(doHeavyLoading, 0)
});

This could be done inside a directive's controller as well.

Edit: As @MarkRajcok pointed out, there would be no render in between $loading = true and $loading = false due to javascript's single-threaded nature. I've added a $timeout to postpone the execution of the heavy loading and give the mask a chance to render.

Fiddle: Working fiddle here Make sure to press 'Run' after the fiddle loads, it won't work on first load because the fiddle waits for all windows to complete.

Upvotes: 3

Related Questions