While learning angular, read a blog which elaborate that
we can access factory/service outside of controller using angular.injector() , But when I try this, it gives my main controller is undefined error and everything stops working.
see the working plunker
with commented culprit code block.Below is main code of lines using angular.injector(["app"]).invoke
var app = angular.module('AlphaModule', []);
// service added
app.service('tea', function(){
return {
teaType: function(teaType) {
console.log('Service => Morning tea must be ' + teaType);
},
sayHello: function(msg) {
console.log('Service => Hello ' + msg);
}
};
});
// ERROR in console when uncomment this code block
angular.injector(["app"]).invoke(function(tea){
tea.sayHello('Yellow');
});
// main controller definition
var AlphaController = function($injector, tea) {
var vm = this;
vm.timeNow = new Date().getTime();
....
};
app.controller('AlphaController', AlphaController );
Please highlight what am I missing/ wrong doing here?
My Guess:
I also read that $injector are singleton . What exactly this means? can we use $injector
only once! or may be this is the issue as i have used $injector in .controller
also
Your module name mentioned is wrong. module name is actualy AlphaModule
not app
.
angular.injector(["AlphaModule"]).invoke(function(tea){
tea.sayHello('Yellow');
});