Quantcast
Viewing latest article 8
Browse Latest Browse All 10

Executing code when all templates have been included – AngularJS

Sometimes, you want to be able to execute code when all the templates have been included in AngularJS using the ng-include attribute. Perhaps, you want to manipulate the inserted HTML…

AngularJS doesn’t provide a method to handle this out of the box, so instead you have to implement it yourself. This is done by utilizing the $includeContentLoaded event, which is fired each time one template has been loaded. Just like the following codesnippet:

scope.$on('$includeContentLoaded', function(event) {
    renderedcount++;
    if (renderedcount == itemmax) {
        // Crappy hack!
        $('.removeparent').unwrap();
        $('.removeparent').removeClass('removeparent');
    }
    console.log('another include was loaded', event.targetScope);
});

Don’t mind the “Crappy hack”-comment…This is just me telling myself, that I should probably refactor this code at some point…*ahem*….

But anyway, you subscribe to the $includeContentLoaded-event, and keep track of all the templates by using a simple counter. When all templates are loaded, you execute the code – which in this instance is jQuery to manipulate the inserted HTML.

It would be nice to have this feature in AngularJS itself – but unfortunately it isn’t. But this way, you can still get what you want…


Image may be NSFW.
Clik here to view.
Image may be NSFW.
Clik here to view.

Viewing latest article 8
Browse Latest Browse All 10

Trending Articles