raulricardo21 raulricardo21 - 1 year ago 91
AngularJS Question

is there a way in Angularjs to define constants with other constants?

I'm trying to define constants with other constants, but it seems that it can't be done, because the initial constant isn't ready when the required constant depending require it. I want to be sure if this isn't possible at all.

Currently I have constants in this way:

angular.module('mainApp.config', [])
.constant('RESOURCE_USERS_DOMAIN', '')
.constant('RESOURCE_USERS_API', '')
// Specific routes for API
.constant('API_SOCIAL_NETWORKS', RESOURCE_USERS_API + '/api/social')

The second two constants is what I want to accomplish

lao lao
Answer Source

The angular way to define dependencies between Controllers, Services and others is by dependency injection (DI). So if you have a controller A that depends on a service B you would have to create it like this.

var myApp = angular.module("exampleApp",[]);

myApp.controller("aCtrl", function(serviceB){
    //Controller functionally here

See, angular will check the serviceB dependency and look for the service you created with that name. If you dont create one you will get an error.

So, if you want to create a constant A that depends on constant B, you would need to tell angular that A depends on B. But constant can't have dependency. Constant can return a function, but the DI won't work for the constant. Check this Fiddle so you can see for which methods DI works: http://jsfiddle.net/RMj5s/1/

So answering your question, you can't define a constant with other constants.

But you can do this:

angular.module('projectApp', [])
  .service('urls',function(domain,api){ this.apiUrl = domain+api;})

  .controller('mainCtrl',function($scope,urls) {

      $scope.url = urls.apiUrl;


Check this fiddle to see it working: http://jsfiddle.net/kJ3tT/1/

If you want to understand more about DI, check out this post: http://merrickchristensen.com/articles/javascript-dependency-injection.html

I hope this can answer your question.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download