raju
raju

Reputation: 4978

How to call service at startup in Angularjs

I want to get config from server and store in global scope in angularjs. I run my app in multiple modes ie development mode and production mode. I interact with few external services which are defferent based on the mode I am in. I can provide then through a rest call to angularjs from expressjs(my server). They are stored in config files of my expressjs.

Is there any controller function which get called at startup? How do I write such a function. Currently my directory structure is

enter image description here

is my directory structure. Are global scope variables in angular js accessible across mudules etc system and auth in above directory?

I also have a init.js in public

//public/init.js
'use strict';

angular.element(document).ready(function() {
    //Fixing facebook bug with redirect
    if (window.location.hash === '#_=_') window.location.hash = '#!';

    //Then init the app
    angular.bootstrap(document, ['mean']);

});

// Dynamically add angular modules declared by packages
var packageModules = [];
for (var index in window.modules) {
    angular.module(window.modules[index].module, window.modules[index].angularDependencies || []);
    packageModules.push(window.modules[index].module);
}

// Default modules
var modules = ['ngCookies', 'ngResource', 'ui.bootstrap', 'ui.router', 'mean.system', 'mean.testcases','mean.testruns',
     'mean.auth'];
modules = modules.concat(packageModules);

// Combined modules
angular.module('mean', modules);

Upvotes: 1

Views: 2395

Answers (2)

pje
pje

Reputation: 2468

If I'm understanding your question correctly, then it sounds like you might want to look into Configuration Blocks in angular modules. These are blocks of code that are run at startup time. Here is the link to the angular doc for modules: https://docs.angularjs.org/guide/module. Search "Configuration Blocks". As far as making it available across the entire app, you might be interested in looking into Providers. Providers can be configured user "Configuration Blocks". You could create a provider that you then configure at startup time based on whatever is in your config file you get from the server.

Upvotes: 3

Dayan Moreno Leon
Dayan Moreno Leon

Reputation: 5435

you can create an App controller right under your ng-app declaration and handle everything there but you really use a service for storing any kind of persistent data. you can also sue ng-init in this app controller to initialize your app when the server renders the page by invoking a function with a server rendered object. There are a few ways to achieve what you want, the best way to do it will depend on your app structure and whether is server rendered or statically served, among other things

Upvotes: 1

Related Questions