Search code examples
javascriptangularjsgulpangular-servicesangular-factory

Value not set to global variable in JS/AngularJs


I am using gulp to run and build to run my application. I am getting file contents using $http service in my index.js file and then setting value of a variable like

window.variablex = "http://localhost:8080/appname".

here is how I am doing it (in index.js)

(function ()
 {
  'use strict';

   angular
    .module('main')
    .controller('IndexController', IndexController);
function IndexController($http){
   $http.get('conf/conf.json').success(function(data){

     window.variable = data.urlValue;

  }).error(function(error){
    console.log(error);
  });
    }
});

And I've created a factory to call the rest APIs of my backend application like

(function(){

  'use strict';

   angular
   .module('main')
   .factory('testService',['$resource',testService]);
     function agentService($resource){
 var agents = $resource('../controller/',{id:'@id'},
  {

    getList:{
      method:'GET',
      url:window.variable+"/controller/index/",
      isArray:false
}
});

Now, I except a rest call to made like

http://localhost:8080/appname/controller

But it always sends a call like http://undefined/appname/controller which is not correct.

I can get the new set value anywhere else, but this value is not being set in resource service objects somehow. I am definitely missing something.

Any help would be much appreciated


Solution

  • @Kenji Mukai's answer did work but I may have to change configuration at run time and there it fails. This is how I achieved it (in case anyone having an issue setting variables before application gets boostrap)

    These are the sets that I followed

    1. Remove ng-app="appName" from your html file as this is what causing problem. Angular hits this tag and bootstraps your application before anything else. hence application is bootstratped before loading data from server-side (in my case)
    2. Added the following in my main module

      var injector = angular.injector(["ng"]);
      var http = injector.get("$http");
         return http.get("conf/conf.json").then(function(response){
          window.appBaseUrl = response.data.gatewayUrl
            }).then(function bootstrapApplication() {
               angular.element(document).ready(function() {
               angular.bootstrap(document, ["yourModuleName"]);
              });
           });
      

    This will load/set new values everytime you refresh your page. You can change conf.json file even at runtime and refreshing the page will take care of updating the values.