AngularJS apps starten en stoppen

AngularJS apps starten en stoppen

Als je gebruik maakt van AngularJS componenten kan je er voor hebben gekozen dat elk component een nieuwe AngularJS app wordt. Je hebt dan nette en kleine componenten die je snel kunt inladen, maar toch kun je tegen problemen aanlopen. Als je bijvoorbeeld routing gebruikt kun je geen apps laden via de ng-app attribute. Routes zullen elkaar overschrijven waardoor apps onverwacht zullen reageren.

Memory leaks voorkomen

Met de app-manager kun je dynamisch een AngularJS app starten en een andere AngularJS app stoppen. Om memory leaks te voorkomen is het belangrijk dat alle scope listeners worden gestopt. Deze oplossing werkt alleen als je architectuur zo is opgezet dat twee componenten niet afhankelijk van elkaar zijn, in dat geval is het verstandig om de componenten samen te voegen in één app.

De appManager

const appManager = new function () {
    let currentAppName,
        currentApp;

    this.bootstrap = function (selector, appName) {
        if (currentApp) {
            this.destroyApp(currentApp);
        }
        var appContainer = document.querySelector(selector);
        if (appContainer) {
            currentAppName = appName;
            currentApp = angular.bootstrap(appContainer, [appName]);
        }
    }

    this.destroyApp = function (app) {
        const $rootScope = app.get('$rootScope');
        $rootScope.$destroy();
    }
}

appManager.bootstrap('body', 'app');
appManager.bootstrap('body', 'app2');

De appManager bestaat uit twee public methodes, bootstrap en destroy. Met bootstrap start je een app, met destory stop je een app. Bij het starten van de app wordt gecontroleerd of er een app actief is, deze wordt vervolgens gestopt om de nieuwe app te kunnen starten.

Plaats de appManager in de window zodat de appManager global beschikbaar is.

Lees ook

How I added my Porsche EV to Homekit

Since my childhood, I have been passionate about cars and everything related to them. Even at a young age, I knew every model. I spent hours flipping through car magazines searching for new facts and always dreamed of owning an exotic car. Initially, I used to dream of owning a Ferrari, but as I grew older and wiser,…

Continue reading

CSS-only Carousel Slider

As a frontend developer, my days are primarily filled with crafting JavaScript-based components using frameworks like Vue, React, or Angular. These frameworks excel at empowering me to create reusable frontend elements, whether it's buttons, modals, links, or accordions. However, as I reflect on my reliance on these…

Continue reading

Homekit `Power consumption` sensor

Recently, I purchased a HomeWizard Wi-Fi P1 Meter. This device provides me with insights into the electricity and gas usage in my home. With 4 solar panels installed, I anticipate generating excess electricity during the spring and summer months. Despite knowing the capacity of the panels, I am unsure of the exact…

Continue reading