Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
163 views
in Technique[技术] by (71.8m points)

javascript - AngularJS constants

Is it possible to inject a constant into another constant with AngularJS?

e.g.

var app = angular.module('myApp');

app.constant('foo', { message: "Hello" } );

app.constant('bar', ['foo', function(foo) { 
    return { 
        message: foo.message + ' World!' 
    } 
}]);

I need the use of an angular constant because I need to inject this into a config routine. i.e.

app.config(['bar', function(bar) {
    console.log(bar.message);
}]);

I know that you can only inject constants and providers into config routines, and my understanding is that you can do dependency injection into providers, however, it does not seem to be the best method for this sort of scenario...

Thanks in advance for your help!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are correct, it's impossible to register both foo and bar as constants.

Also for using a provider as a workaround, you almost got it right except that you have to store data in a provider instance:

var app = angular.module('myApp', []);

app.constant('foo', {
    message: 'Hello'
});

app.provider('bar', ['foo', function(foo) {
  this.data = {
    message: foo.message + ' World!'
  };

  this.$get = function() {
    return this.data;
  };
}]);

and then in config block, inject a bar's provider instance (not a bar instance as it isn't available yet in the config phase):

app.config(['barProvider', function(barProvider) {
  console.log(barProvider.data.message);
}]);

Hope this helps.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...