2

I have an app that I have inherited that I have to support. So far it had only run on one server and we want to run it on different servers. We found hard coded references to the server name all over the place in python server code and C++ client code. It was easy enough to change those to read the server name from a config file. But now I find is a js module this code:

angular.module('app.config', []).constant('config', {"api":"http://foo.bar.com:8001/"});

How can I change this so that the value for the server is read dynamically from a config file or some other means that would not require it to be hard coded?

Here is an update with what I have tried:

Originally, my code had this:

angular.module('app.config', []).constant(
  'config', {"api":"http://foo.bar.com:8001/"}
);

and I changed it to this:

angular.module('app.config').controller('myCtrl', 
  function($scope, $http) { 
    $http.get('./config.json') 
      .then(function(response) { 
        $scope.api = response.data; 
    }); 
});

and I got this:

error Module 'app.config' is not available!

Then I changed it to:

angular.module('app.config', [] ).controller('myCtrl', 
  function($scope, $http) { 
    $http.get('./config.json') 
      .then(function(response) { 
        $scope.api = response.data; 
      }); 
});

And then I get:

Error: [$injector:unpr] Unknown provider: configProvider <- config <- workitem

I feel I am very close, I just need a bit more help.

Another update:

I tried this:

angular.module('app').controller('home', ['$scope', homeCtrl]);
angular.module('app').controller('workitem', ['$scope', '$routeParams', '$sce', '$timeout', '$http', 'config', workitemCtrl]);
},{"./home/home.js":3,"./workitem/workitem.js":4,"angular":10,"angular-route":6,"angular-sanitize":8,"bootstrap-treeview/src/js/bootstrap-treeview.js":11}],2:[function(require,module,exports){
  module.exports = function($scope,$http) {
      $http.get('config.json').success(function(reponse) {
          console.log("reponse --> "+reponse.api);
          $scope.api = reponse.api;
      });
  }

But then of course app.config was not getting defined. How could I do this an still define app.config?

I just tried this:

var my_config = {};

$.getJSON("config.json", function(data) {
  $.each(data, function(key, val) {
    my_config[key] = val;
  });
});

but I get my_config is not defined when I use it down in the controller. How can I make that variable available in the controller?

6
  • do you mean a separate .json file? Commented May 9, 2016 at 13:58
  • 1
    Are you using a build tool like grunt or gulp?? Commented May 9, 2016 at 14:00
  • Separate from what? The config file I am using for our python and C++ code is simple key values pairs. I'd like to use the same file for this as well. Commented May 9, 2016 at 14:01
  • if you use some builder like grunt you can easily pass it a Json configuration file, and have the build tool replace placeholder strings in the JS with values from said conf file Commented May 9, 2016 at 14:01
  • No we are not using any build tools. That would probably be overkill for us - right now we just want to deploy on 2 hosts. Maybe a few more down the road, but all in house. I just don't want to have a different js file for each host. Commented May 9, 2016 at 14:03

4 Answers 4

3

Try This

angular.module('app.config', [])
.constant('bbConfig',{ 
     "api":"http://foo.bar.com:8001/"
 });

In controller

angular.module('app.config', [])
.controller('MainCtrl',['$scope', 'bbConfig' , function ($scope, bbConfig){
    console.log(bbConfig.api)
}]);
Sign up to request clarification or add additional context in comments.

2 Comments

I like this solution because this file now becomes just a normal config file. In other words, it stops living in the release and is instead managed in each instance it is deployed.
Where would I put the code in the first block? In a file? Where is that file referenced?
0

Create a service to read the config (json file) or make a call to server and store the response URL in LocalStorage like the following. You can access it from every where

$localStorage.api = response.Url ; // http://foo.bar.com:8001/

Comments

0

I was finally able to get this working by doing this up front:

angular.module('app').value('config', {
  api: ''
});

angular.module('app').run(function($rootScope, $http, config) {
  $http.get('config/config.json').then(function(response) {
        config.api = response.data.api;
        $rootScope.$broadcast('config-loaded');
    });
});

Wrapping the main code in:

var init = function(){
}

And adding this at the end:

if (config.api) {
  init()
} else {
    var configLoaded = scope.$on('config-loaded', function() {
        init();
        configLoaded();
    });
}

Comments

0

You can do:

  1. Use ngConstant build task to wrap your standalone config file in JSON format into the includable angular.config data. Suppose you have app/config.json file:

    { "myFirstCnt": true, "mySecondCnt": { "hello": "world" } }

Then after running the ngConstant task in you build you'll get dist/config.js (output) will be :

define(["require", "exports"], function(require, exports) {
  return angular.module("my.module.config", ["ngAnimate"])
    .constant("myFirstCnt", true)
    .constant("mySecondCnt", { "hello": "world" })
    .constant("myPropCnt", "hola!");
});

Gulp plugin, Grunt plugin, more on ngConstant

  1. Use service to load the JSON file immediately after you app bootstraps in service or in the controller:

should avoid this:

app.controller('myCtrl', 
  function($scope, $http) {
    $http.get('PATH_TO/config.json').then(function(response) {
      $scope.myWelcome = response.data;
    });
  }
);

More on that way example here: Reading in JSON through Angular Resources Service

UPD 12-06

For parsing loaded JSON try this:

for (var name in data) {
  if (data.hasOwnProperty(var)) {
     my_config[var] = data[var];
  }
}

13 Comments

More info on this method.
@Ankh, that one is about AngularJS 2.x version, while here it's 1.x
When I used app.controller I got an error. I changed it to this: angular.module('app').controller('myCtrl', function($scope, $http) { $http.get('./config.json') .then(function(response) { $scope.api = response.data; }); }); and now later in the script when app.config is referenced I get the error Module 'app.config' is not available!
you should reference $scope.api as you pass data to it in that code line: $scope.api = response.data; or change the naming onto $rootScope.api, then it will be available in all controllers
Guess I am not understanding what I need to do. I changed all the references to $scope.config.api to $scope.api but I get the same error. Also tried changing the assignment to$rootScope.api = response.data and got the same error.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.